Java 类java.sql.DriverManager 实例源码

项目:Roaster-Management-Application    文件:Register.java   
public boolean register_user(String username,String pwd,String f_name,String l_name,String role)
{
    try{

        Class.forName("com.mysql.jdbc.Driver");  
        Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/icms_employees?autoReconnect=true&useSSL=false","root","admin");  
        Statement st = con.createStatement();
        st.executeUpdate("insert into `employees`(`first_name`,`last_name`,`username`,`password`,`role`) VALUES('"+f_name+"','"+l_name+"','"+username+"','"+pwd+"','"+role+"')");
        registration_success=true;
        st.close();
        con.close();

} catch(Exception e) {
    System.out.println(e.getMessage());
}

    return registration_success;

}
项目:otus_java_2017_04    文件:ConnectionHelper.java   
public static Connection getConnection() {
    try {
        DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver());

        String url = "jdbc:mysql://" +       //db type
                "localhost:" +               //host name
                "3306/" +                    //port
                "db_example?" +              //db name
                "useSSL=false&" +            //do not use ssl
                "user=tully&" +              //login
                "password=tully";            //password

        return DriverManager.getConnection(url);
    } catch (SQLException e) {
        throw new RuntimeException(e);
    }
}
项目:MybatisGeneatorUtil    文件:SqlScriptRunner.java   
public void executeScript() throws Exception {

        Connection connection = null;

        try {
            Class.forName(driver);
            connection = DriverManager.getConnection(url, userid, password);

            Statement statement = connection.createStatement();

            BufferedReader br = new BufferedReader(new InputStreamReader(sourceFile));

            String sql;

            while ((sql = readStatement(br)) != null) {
                statement.execute(sql);
            }

            closeStatement(statement);
            connection.commit();
            br.close();
        } finally {
            closeConnection(connection);
        }
    }
项目:uavstack    文件:JdbcDriverIT.java   
/**
 * do register driver
 * 
 * @param dr
 */
public Driver doRegisterDriver(Driver dr, boolean needRegisterToDriverManager) {

    try {
        if (needRegisterToDriverManager == true) {
            DriverManager.deregisterDriver(dr);
        }

        Driver drProxy = JDKProxyInvokeUtil.newProxyInstance(this.getClass().getClassLoader(),
                new Class<?>[] { Driver.class }, new JDKProxyInvokeHandler<Driver>(dr, new DriverProxy()));

        if (needRegisterToDriverManager == true) {
            DriverManager.registerDriver(drProxy);
        }

        return drProxy;
    }
    catch (SQLException e) {
        logger.error("Install JDBC Driver Proxy FAIL.", e);
    }

    return dr;

}
项目:AlphaLibary    文件:SQLiteAPI.java   
/**
 * Gets the {@link Connection} to the database
 *
 * @return the {@link Connection}
 */
public Connection getSQLiteConnection() {
    if (isConnected()) {
        return CONNECTIONS.get(this.getDatabasePath());
    } else {
        try {
            closeSQLiteConnection();

            Class.forName("org.sqlite.JDBC");
            Connection c = DriverManager.getConnection(
                    "jdbc:sqlite:" + this.getDatabasePath());

            CONNECTIONS.put(this.getDatabasePath(), c);

            return c;
        } catch (SQLException | ClassNotFoundException ignore) {
            Bukkit.getLogger().log(Level.WARNING, "Failed to reconnect to " + this.getDatabasePath() + "! Check your sqllite.json inside AlphaLibary");
            return null;
        }
    }
}
项目:QDrill    文件:TestJdbcDistQuery.java   
@Test
public void testSchemaForEmptyResultSet() throws Exception {
  String query = "select fullname, occupation, postal_code from cp.`customer.json` where 0 = 1";
  try (Connection c = DriverManager.getConnection("jdbc:drill:zk=local", null);) {
    Statement s = c.createStatement();
    ResultSet r = s.executeQuery(query);
    ResultSetMetaData md = r.getMetaData();
    List<String> columns = Lists.newArrayList();
    for (int i = 1; i <= md.getColumnCount(); i++) {
      System.out.print(md.getColumnName(i));
      System.out.print('\t');
      columns.add(md.getColumnName(i));
    }
    String[] expected = {"fullname", "occupation", "postal_code"};
    Assert.assertEquals(3, md.getColumnCount());
    Assert.assertArrayEquals(expected, columns.toArray());
    // TODO:  Purge nextUntilEnd(...) and calls when remaining fragment race
    // conditions are fixed (not just DRILL-2245 fixes).
    nextUntilEnd(r);
  }
}
项目:big_data    文件:JdbcManager.java   
/**
 * 根据配置获取获取关系型数据库的jdbc连接
 * 
 * @param conf
 *            hadoop配置信息
 * @param flag
 *            区分不同数据源的标志位
 * @return
 * @throws SQLException
 */
public static Connection getConnection(Configuration conf, String flag) throws SQLException {
    String driverStr = String.format(GlobalConstants.JDBC_DRIVER, flag);
    String urlStr = String.format(GlobalConstants.JDBC_URL, flag);
    String usernameStr = String.format(GlobalConstants.JDBC_USERNAME, flag);
    String passwordStr = String.format(GlobalConstants.JDBC_PASSWORD, flag);

    String driverClass = conf.get(driverStr);
    // String url = conf.get(urlStr);
    String url = "jdbc:mysql://hadoop1:3306/result_db?useUnicode=true&amp;characterEncoding=utf8";
    // String username = conf.get(usernameStr);
    // String password = conf.get(passwordStr);
    try {
        Class.forName("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException e) {
        // nothing
    }
    return DriverManager.getConnection(url, "root", "root");
}
项目:Course-Management-System    文件:StudentCourseOutlineDAO.java   
public StudentCourseOutlineDAO(Student student)throws Exception{
    Properties properties = new Properties();
    properties.load(StudentCourseOutlineDAO.class.getResourceAsStream("/details.properties"));
    String dbname=properties.getProperty("dbName");
    String user=properties.getProperty("user");
    String password=properties.getProperty("password");
    try{System.out.println("StudentCourseOutlineDAO");
    myCon=DriverManager.getConnection(dbname, user, password);
    /*
     * For Debugging Purpose
     */
    //System.out.println("Connection Established");
    }catch(SQLException exc){
        System.out.println("Connection Problem::: Message ::");
        exc.printStackTrace();
    }

    this.student = student;
    if(student == null){
        System.exit(0);
    }
}
项目:Equella    文件:DatabaseConnectCallback.java   
public void testDatabase(String driver, String connectionUrl, String username, String password, String dbtype,
    String database) throws SQLException, ClassNotFoundException, NonUnicodeEncodingException
{
    Connection connection = null;
    try
    {
        // We USED to use Hibernate but I removed it due to ClassLoader
        // issues. So shoot me...
        Class.forName(driver);
        connection = DriverManager.getConnection(connectionUrl, username, password);
        DatabaseCommand.ensureUnicodeEncoding(connection, dbtype, database);
    }
    catch( SQLException pain )
    {
        throw new RuntimeException("Attempted connect at connectionURL (" + connectionUrl + "), username ("
            + username + "), password(" + password + "), dbtype(" + dbtype + "), database(" + database + ')', pain);
    }
    finally
    {
        if( connection != null )
        {
            connection.close();
        }
    }
}
项目:calcite-avatica    文件:RemoteMetaTest.java   
@Test public void testOpenConnectionWithProperties() throws Exception {
  // This tests that username and password are used for creating a connection on the
  // server. If this was not the case, it would succeed.
  try {
    DriverManager.getConnection(url, "john", "doe");
    fail("expected exception");
  } catch (RuntimeException e) {
    assertEquals("Remote driver error: RuntimeException: "
        + "java.sql.SQLInvalidAuthorizationSpecException: invalid authorization specification"
        + " - not found: john"
        + " -> SQLInvalidAuthorizationSpecException: invalid authorization specification - "
        + "not found: john"
        + " -> HsqlException: invalid authorization specification - not found: john",
        e.getMessage());
  }
}
项目:calcite-avatica    文件:RemoteMetaTest.java   
@Test public void testRemoteStatementInsert() throws Exception {
  ConnectionSpec.getDatabaseLock().lock();
  try {
    final String t = AvaticaUtils.unique("TEST_TABLE2");
    AvaticaConnection conn = (AvaticaConnection) DriverManager.getConnection(url);
    Statement statement = conn.createStatement();
    final String create =
        String.format(Locale.ROOT, "create table if not exists %s ("
            + "  id int not null, msg varchar(255) not null)", t);
    int status = statement.executeUpdate(create);
    assertEquals(status, 0);

    statement = conn.createStatement();
    final String update =
        String.format(Locale.ROOT, "insert into %s values ('%d', '%s')",
            t, RANDOM.nextInt(Integer.MAX_VALUE), UUID.randomUUID());
    status = statement.executeUpdate(update);
    assertEquals(status, 1);
  } finally {
    ConnectionSpec.getDatabaseLock().unlock();
  }
}
项目:elastic-db-tools-for-java    文件:SqlDatabaseUtils.java   
static void executeSqlScript(String server,
        String db,
        String schemaFile) {
    ConsoleUtils.writeInfo("Executing script %s", schemaFile);
    try (Connection conn = DriverManager.getConnection(Configuration.getConnectionString(server, db))) {
        try (Statement stmt = conn.createStatement()) {
            // Read the commands from the sql script file
            ArrayList<String> commands = readSqlScript(schemaFile);

            for (String cmd : commands) {
                stmt.execute(cmd);
            }
        }
    }
    catch (SQLException e) {
        e.printStackTrace();
    }
}
项目:elastic-db-tools-for-java    文件:ShardMapManagerTests.java   
/**
 * Cleans up common state for the all tests in this class.
 */
@AfterClass
public static void shardMapManagerTestsCleanup() throws SQLException {
    Connection conn = null;
    try {
        conn = DriverManager.getConnection(Globals.SHARD_MAP_MANAGER_TEST_CONN_STRING);
        // Create ShardMapManager database
        try (Statement stmt = conn.createStatement()) {
            String query = String.format(Globals.DROP_DATABASE_QUERY, Globals.SHARD_MAP_MANAGER_DATABASE_NAME);
            stmt.executeUpdate(query);
        }
        catch (SQLException ex) {
            ex.printStackTrace();
        }
    }
    catch (Exception e) {
        System.out.printf("Failed to connect to SQL database with connection string: " + e.getMessage());
    }
    finally {
        if (conn != null && !conn.isClosed()) {
            conn.close();
        }
    }
}
项目:AlphaLibary    文件:MySQLConnector.java   
@Override
public Connection connect() {
    if (handler.isConnected()) {
        return SQLConnectionHandler.getConnectionMap().get(handler.getInformation().getDatabaseName());
    } else {
        try {
            handler.disconnect();

            Connection c = DriverManager.getConnection(
                    "jdbc:mysql://" + handler.getInformation().getHost() + ":" + handler.getInformation().getPort() + "/" + handler.getInformation().getDatabaseName() + "?autoReconnect=true", handler.getInformation().getUserName(), handler.getInformation().getPassword());

            SQLConnectionHandler.getConnectionMap().put(handler.getInformation().getDatabaseName(), c);

            return c;
        } catch (SQLException ignore) {
            Bukkit.getLogger().log(Level.WARNING, "Failed to connect to " + handler.getInformation().getDatabaseName() + "! Check your mysql.yml inside the folder of " + handler.getPlugin().getName());
            return null;
        }
    }
}
项目:dev-courses    文件:TestSqlPersistent.java   
protected void setUp() throws Exception {

        super.setUp();

        user       = "sa";
        password   = "";
        stmnt      = null;
        connection = null;

        TestUtil.deleteDatabase("/hsql/test/testpersistent");

        try {
            Class.forName("org.hsqldb.jdbc.JDBCDriver");

            connection = DriverManager.getConnection(url, user, password);
            stmnt      = connection.createStatement();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("TestSqlPersistence.setUp() error: "
                               + e.getMessage());
        }
    }
项目:incubator-netbeans    文件:MetadataElementHandleTest.java   
@Override
public void setUp() throws Exception {
    clearWorkDir();
    Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
    conn = DriverManager.getConnection("jdbc:derby:" + getWorkDirPath() + "/test;create=true");
    Statement stmt = conn.createStatement();
    stmt.executeUpdate("CREATE TABLE FOO (" +
            "ID INT NOT NULL PRIMARY KEY, " +
            "FOO VARCHAR(16))");
    stmt.executeUpdate("CREATE TABLE BAR (ID INT NOT NULL PRIMARY KEY, FOO_ID INT NOT NULL, FOREIGN KEY (FOO_ID) REFERENCES FOO)");
    stmt.executeUpdate("CREATE INDEX FOO_INDEX ON FOO(FOO)");
    stmt.executeUpdate("CREATE VIEW FOOVIEW AS SELECT * FROM FOO");
    stmt.executeUpdate("CREATE PROCEDURE XY (IN S_MONTH INTEGER, IN S_DAYS VARCHAR(255)) "
            + " DYNAMIC RESULT SETS 1 "
            + " PARAMETER STYLE JAVA READS SQL  DATA LANGUAGE JAVA "
            + " EXTERNAL NAME 'org.netbeans.modules.db.metadata.model.api.MetadataElementHandleTest.demoProcedure'");
    stmt.executeUpdate("CREATE FUNCTION TO_DEGREES(RADIANS DOUBLE) RETURNS DOUBLE "
            + "PARAMETER STYLE JAVA NO SQL LANGUAGE JAVA "
            + "EXTERNAL NAME 'java.lang.Math.toDegrees'");
    stmt.close();
    metadata = new JDBCMetadata(conn, "APP").getMetadata();
}
项目:incubator-netbeans    文件:JDBCMetadataDerbyTest.java   
@Override
public void setUp() throws Exception {
    clearWorkDir();
    Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
    conn = DriverManager.getConnection("jdbc:derby:" + getWorkDirPath() + "/test;create=true");
    stmt = conn.createStatement();
    stmt.executeUpdate("CREATE TABLE FOO (" +
            "ID INT NOT NULL, " +
            "FOO_NAME VARCHAR(16), " +
            "CONSTRAINT FOO_PK PRIMARY KEY (ID, FOO_NAME))");
    stmt.executeUpdate("CREATE TABLE BAR (" +
            "\"i+d\" INT NOT NULL PRIMARY KEY, " +
            "FOO_ID INT NOT NULL, " +
            "FOO_NAME VARCHAR(16) NOT NULL, " +
            "BAR_NAME VARCHAR(16) NOT NULL, " +
            "DEC_COL DECIMAL(12,2), " +
            "FOREIGN KEY (FOO_ID, FOO_NAME) REFERENCES FOO(ID, FOO_NAME))");
    stmt.executeUpdate("CREATE VIEW BARVIEW AS SELECT * FROM BAR");

    stmt.executeUpdate("CREATE INDEX BAR_INDEX ON BAR(FOO_ID ASC, FOO_NAME DESC)");
    stmt.executeUpdate("CREATE UNIQUE INDEX DEC_COL_INDEX ON BAR(DEC_COL)");
    metadata = new JDBCMetadata(conn, "APP");
}
项目:incubator-netbeans    文件:DbDriverManagerTest.java   
/**
 * Tests that drivers from DriverManager are loaded.
 */
public void testLoadFromDriverManager() throws Exception {
    final String URL = "jdbc:testLoadFromDriverManager";

    Driver d = new DriverImpl(URL);
    DriverManager.registerDriver(d);
    try {
        Driver found = DbDriverManager.getDefault().getDriver(URL, null);
        assertSame(d, found);
        Connection conn = DbDriverManager.getDefault().getConnection(URL, new Properties(), null);
        assertNotNull(conn);
        assertSame(d, ((ConnectionEx)conn).getDriver());
    } finally {
        DriverManager.deregisterDriver(d);
    }
}
项目:elastic-db-tools-for-java    文件:ShardMapManagerLoadTests.java   
/**
 * Kill all connections to Shard Map Manager database.
 */
@Test
@Category(value = ExcludeFromGatedCheckin.class)
public final void loadTestKillGsmConnections() throws SQLException {
    // Clear all connection pools.
    try (Connection conn = DriverManager.getConnection(Globals.SHARD_MAP_MANAGER_TEST_CONN_STRING)) {
        try (Statement stmt = conn.createStatement()) {
            String query = String.format(KILL_CONNECTIONS_FOR_DATABASE_QUERY, Globals.SHARD_MAP_MANAGER_DATABASE_NAME);
            stmt.execute(query);
        }
    }
    catch (SQLException e) {
        // 233: A transport-level error has occurred when receiving results from the server.
        // (provider: Shared Memory Provider,
        // error: 0 - No process is on the other end of the pipe.)
        // 6106: Process ID %d is not an active process ID.
        // 6107: Only user processes can be killed
        if ((e.getErrorCode() != 233) && (e.getErrorCode() != 6106) && (e.getErrorCode() != 6107)) {
            Assert.fail(String.format("error number %1$s with message %2$s", e.getErrorCode(), e.getMessage()));
        }
    }
}
项目:mountieLibrary    文件:MountieQueries.java   
/**
 * Constructor with arguments; used to search a record that matched 2 parameter.
 * @param sql The SQL statement to be executed.
 * @param search1 The first specific record attribute to be search for.
 * @param search2 The second specific record attribute to be search for.
 */
public MountieQueries(String sql, String search1, String search2) {
    try{
        setSQL(sql);

        //get the connection to database
        connection = DriverManager.getConnection(URL, userDB, passDB); 

        //prepatre statements
        preparedStatment = connection.prepareStatement(sql);

        //set parameters
        preparedStatment.setString(1, search1);
        preparedStatment.setString(2, search2);

        //execute query
        resultSet = preparedStatment.executeQuery();
    }
    catch (SQLException sqlException) {
        sqlException.printStackTrace();
        displayAlert(Alert.AlertType.ERROR,"Error" , 
            "Data base could not be loaded", searchString);
        System.exit(1);
    } 
}
项目:quorrabot    文件:SqliteStore.java   
private static Connection CreateConnection(String dbname, int cache_size, boolean safe_write, boolean journal, boolean autocommit) {
    Connection connection = null;

    try {
        SQLiteConfig config = new SQLiteConfig();
        config.setCacheSize(cache_size);
        config.setSynchronous(safe_write ? SQLiteConfig.SynchronousMode.FULL : SQLiteConfig.SynchronousMode.NORMAL);
        config.setTempStore(SQLiteConfig.TempStore.MEMORY);
        config.setJournalMode(journal ? SQLiteConfig.JournalMode.TRUNCATE : SQLiteConfig.JournalMode.OFF);
        connection = DriverManager.getConnection("jdbc:sqlite:" + dbname.replaceAll("\\\\", "/"), config.toProperties());
        connection.setAutoCommit(autocommit);
    } catch (SQLException ex) {
        com.gmt2001.Console.err.printStackTrace(ex);
    }

    return connection;
}
项目:PetBlocks    文件:DatabaseIT.java   
@Test
public void enableDatabaseMySQLTest() {
    try {
        final DB database = DB.newEmbeddedDB(3306);
        database.start();
        try (Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/?user=root&password=")) {
            try (Statement statement = conn.createStatement()) {
                statement.executeUpdate("CREATE DATABASE db");
            }
        }
        final HikariConfig config = new HikariConfig();
        config.setDriverClassName("com.mysql.jdbc.Driver");
        config.setConnectionTestQuery("SELECT 1");
        config.setJdbcUrl("jdbc:mysql://localhost:3306/db");
        config.setMaxLifetime(60000);
        config.setIdleTimeout(45000);
        config.setMaximumPoolSize(50);
        final HikariDataSource ds = new HikariDataSource(config);
        ds.close();
        database.stop();
    } catch (final Exception ex) {
        Logger.getLogger(this.getClass().getSimpleName()).log(Level.WARNING, "Failed to enable database.", ex);
        Assert.fail();
    }
}
项目:Transwarp-Sample-Code    文件:Connector.java   
/**
 * 创建Inceptor的JDBC连接
 * @return JDBC连接
 */
public static Connection getConnection() {
    Connection connection = null;
    try {
        if (Constant.MODE.equals("simple")) {
            connection = DriverManager.getConnection(Constant.SIMPLE_JDBC_URL);
        } else if (Constant.MODE.equals("LDAP")) {
            connection = DriverManager.getConnection(Constant.LDAP_JDBC_URL,
                    Constant.LDAP_NAME, Constant.LDAP_PASSWD);
        } else {
            connection = DriverManager.getConnection(Constant.KERBEROS_JDBC_URL);
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return connection;
}
项目:SkyWarsReloaded    文件:Database.java   
private void connect() throws SQLException {
    if (connection != null) {
        try {
            connection.createStatement().execute("SELECT 1;");

        } catch (SQLException sqlException) {
            if (sqlException.getSQLState().equals("08S01")) {
                try {
                    connection.close();

                } catch (SQLException ignored) {
                }
            }
        }
    }

    if (connection == null || connection.isClosed()) {
        connection = DriverManager.getConnection(connectionUri, username, password);
    }
}
项目:mczone    文件:MySQL.java   
public Connection open() {
    String url = "";
    try {
        url = "jdbc:mysql://"
                + this.hostname
                + ":"
                + this.portnmbr
                + "/"
                + this.database
                + "?connectTimeout=3000&zeroDateTimeBehavior=convertToNull&autoReconnect=true&failOverReadOnly=false&maxReconnects=10";
        this.connection = DriverManager.getConnection(url, this.username, this.password);
        return this.connection;
    } catch (SQLException e) {
        e.printStackTrace();
    }
    return null;
}
项目:endpoint-health    文件:EndPointHealthServiceImpl.java   
private void createChangelogTable() {
    try (Connection con = DriverManager
            .getConnection(Utils.getDatabaseUrl(endPointHealthConfiguration.databaseFile()),
                endPointHealthConfiguration.databaseUser(), endPointHealthConfiguration.databasePassword());
            Statement st = con.createStatement()) {

        con.setAutoCommit(true);

        final String sql = FileUtils.readFileToString(
            new File(endPointHealthConfiguration.sqlDirectory(), "changelog.sql"),
            Charset.forName("UTF-8"));

        LOGGER.info("Creating changelog table");

        st.execute(sql);
    } catch (SQLException | IOException e) {
        throw new EndPointHealthException(e);
    }
}
项目:docker-compose-rule-with-junit5    文件:SimpleTest.java   
@Test
public void shouldConnectToDatabase(DockerComposeRule docker) throws SQLException, ClassNotFoundException {
    // Given
    // We need to import the driver https://jdbc.postgresql.org/documentation/head/load.html
    Class.forName("org.postgresql.Driver");

    DockerPort container = docker.containers().container("postgres").port(5432);
    String url = "jdbc:postgresql://" + container.getIp() + ":" + container.getExternalPort() + "/postgres";
    Connection connection = DriverManager.getConnection(url, "postgres", "ThisIsMySuperPassword");

    // When
    ResultSet resultSet = connection.prepareStatement("SELECT 1").executeQuery();

    // Then
    assertNotNull(resultSet);
}
项目:sstore-soft    文件:JavaSystem.java   
public static void setLogToSystem(boolean value) {

//#ifdef JAVA2FULL
        try {
            PrintWriter newPrintWriter = (value) ? new PrintWriter(System.out)
                                                 : null;

            DriverManager.setLogWriter(newPrintWriter);
        } catch (Exception e) {}

//#else
/*
        try {
            PrintStream newOutStream = (value) ? System.out
                                               : null;
            DriverManager.setLogStream(newOutStream);
        } catch (Exception e){}
*/

//#endif
    }
项目:mdw-demo    文件:MariaDBEmbeddedDb.java   
public void source(String contents) throws SQLException {
    Scanner s = new Scanner(contents);
    s.useDelimiter("(;(\r)?\n)|(--\n)");
    Connection connection = null;
    Statement statement = null;
    try {
        Class.forName(getDriverClass());
        connection = DriverManager.getConnection(url, this.user, password);
        statement = connection.createStatement();
        while (s.hasNext()) {
            String line = s.next();
            if (line.startsWith("/*!") && line.endsWith("*/")) {
                int i = line.indexOf(' ');
                line = line.substring(i + 1, line.length() - " */".length());
            }

            if (line.trim().length() > 0) {
                statement.execute(line);
            }
        }
    }
    catch (ClassNotFoundException ex) {
        throw new SQLException("Cannot locate JDBC driver class", ex);
    }

    finally {
        s.close();
        if (statement != null)
            statement.close();
        if (connection != null)
            connection.close();
    }
}
项目:nh-micro    文件:MicroXaDataSource.java   
private Connection recreateConn(Connection conn) throws SQLException {

        log.debug("recreating conn xid="+getStr4XidLocal());
        if(conn!=null){
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            conn=null;
        }
        Connection connection=DriverManager.getConnection(url, username, password); 
        connection.setAutoCommit(false);
        connection.setTransactionIsolation(level);

        return connection;
    }
项目:AlphaLibary    文件:MySQLAPI.java   
/**
 * Gets the {@link Connection} to the database
 *
 * @return the {@link Connection}
 */
public Connection getMySQLConnection() {
    if (isConnected()) {
        return CONNECTIONS.get(database);
    } else {
        try {
            Connection c = DriverManager.getConnection(
                    "jdbc:mysql://" + host + ":" + port + "/" + database + "?autoReconnect=true", username, password);

            CONNECTIONS.put(database, c);

            return c;
        } catch (SQLException ignore) {
            Bukkit.getLogger().log(Level.WARNING, "Failed to reconnect to " + database + "! Check your sql.yml inside AlphaGameLibary");
            return null;
        }
    }
}
项目:s-store    文件:TestJDBCDriver.java   
private static void startServer() throws ClassNotFoundException, SQLException {
    CatalogContext catalogContext = CatalogUtil.loadCatalogContextFromJar(new File(testjar)) ;
    HStoreConf hstore_conf = HStoreConf.singleton(HStoreConf.isInitialized()==false);
    Map<String, String> confParams = new HashMap<String, String>();
    hstore_conf.loadFromArgs(confParams);
    server = new ServerThread(catalogContext, hstore_conf, 0);

    server.start();
    server.waitForInitialization();

    Class.forName("org.voltdb.jdbc.Driver");

    conn = DriverManager.getConnection("jdbc:voltdb://localhost:21212");  
    myconn = null;
}
项目:calcite-avatica    文件:AlternatingRemoteMetaTest.java   
@Test public void testQuery() throws Exception {
  ConnectionSpec.getDatabaseLock().lock();
  try (AvaticaConnection conn = (AvaticaConnection) DriverManager.getConnection(url);
      Statement statement = conn.createStatement()) {
    assertFalse(statement.execute("SET SCHEMA \"SCOTT\""));
    assertFalse(
        statement.execute(
            "CREATE TABLE \"FOO\"(\"KEY\" INTEGER NOT NULL, \"VALUE\" VARCHAR(10))"));
    assertFalse(statement.execute("SET TABLE \"FOO\" READONLY FALSE"));

    final int numRecords = 1000;
    for (int i = 0; i < numRecords; i++) {
      assertFalse(statement.execute("INSERT INTO \"FOO\" VALUES(" + i + ", '" + i + "')"));
    }

    // Make sure all the records are there that we expect
    ResultSet results = statement.executeQuery("SELECT count(KEY) FROM FOO");
    assertTrue(results.next());
    assertEquals(1000, results.getInt(1));
    assertFalse(results.next());

    results = statement.executeQuery("SELECT KEY, VALUE FROM FOO ORDER BY KEY ASC");
    for (int i = 0; i < numRecords; i++) {
      assertTrue(results.next());
      assertEquals(i, results.getInt(1));
      assertEquals(Integer.toString(i), results.getString(2));
    }
  } finally {
    ConnectionSpec.getDatabaseLock().unlock();
  }
}
项目:OrthancAnonymization    文件:JDBCConnector.java   
public JDBCConnector() throws ClassNotFoundException, SQLException{
    Class.forName("com.mysql.jdbc.Driver");
    if(jprefer.get("dbAdress", null) != null && jprefer.get("dbPort", null) != null && jprefer.get("dbName", null) != null &&
            jprefer.get("dbUsername", null) != null && jprefer.get("dbPassword", null) != null){
        connection = DriverManager.getConnection("jdbc:mysql://" + jprefer.get("dbAdress", null) + ":" 
            + jprefer.get("dbPort", null)  + "/" + jprefer.get("dbName", null), jprefer.get("dbUsername", null), jprefer.get("dbPassword", null));
    }
}
项目:openjdk-jdk10    文件:DriverManagerModuleTests.java   
/**
 * Validate JDBC drivers as modules will be accessible. One driver will be
 * loaded and registered via the service-provider loading mechanism. The
 * other driver will need to be explictly loaded
 *
 * @throws java.lang.Exception
 */
@Test
public void test() throws Exception {
    System.out.println("\n$$$ runing Test()\n");
    dumpRegisteredDrivers();
    Driver d = DriverManager.getDriver(STUBDRIVERURL);
    assertNotNull(d, "StubDriver should not be null");
    assertTrue(isDriverRegistered(d));
    Driver d2 = null;

    // This driver should not be found until it is explictly loaded
    try {
        d2 = DriverManager.getDriver(LUCKYDOGDRIVER_URL);
    } catch (SQLException e) {
        // ignore expected Exception
    }
    assertNull(d2, "LuckyDogDriver should  be null");
    loadDriver();
    d2 = DriverManager.getDriver(LUCKYDOGDRIVER_URL);
    assertNotNull(d2, "LuckyDogDriver should not be null");
    assertTrue(isDriverRegistered(d2), "Driver was NOT registered");

    dumpRegisteredDrivers();
    DriverManager.deregisterDriver(d2);
    assertFalse(isDriverRegistered(d2), "Driver IS STILL registered");
    dumpRegisteredDrivers();

}
项目:ArchersBattle    文件:Main.java   
public void onEnable() {
    Bukkit.getConsoleSender().sendMessage("§6§lArchersBattle §7>>> §a弓箭手大作战正在加载中..");
    instance = this;
    Bukkit.getPluginCommand("ab").setExecutor(new Commands());
    Bukkit.getPluginCommand("abadmin").setExecutor(new AdminCommands());
    Bukkit.getPluginManager().registerEvents(new InventoryListener(), this);
    Bukkit.getPluginManager().registerEvents(new WorldListener(), this);
    Bukkit.getPluginManager().registerEvents(new PlayerListener(), this);
    Bukkit.getPluginManager().registerEvents(new ProjectileListener(), this);
    new SkillManager();
    loadSkills();
    loadArenas();
    ItemManager.init();
    new Messages();
    new ConfigManager(this);
    new CooldownManager();
    new UpgradeManager();
    Database db = null;
    try {
        db = new Database(DriverManager.getConnection(ConfigManager.getConfigManager().getMySQLAddress(),
                ConfigManager.getConfigManager().getMySQLUser(),
                ConfigManager.getConfigManager().getMySQLPassword()));
    } catch (SQLException e) {
        e.printStackTrace();
    }
    if (!db.init()) {
        Bukkit.getConsoleSender().sendMessage("§6§lArchersBattle §7>>> §c数据库初始化失败,停止加载");
        setEnabled(false);
    }
    new XpManager();
    new Metrics(instance);
    Bukkit.getConsoleSender().sendMessage("§6§lArchersBattle §7>>> §a加载完成!加载了" + SkillManager.getInstance().getSkills().size() + "个技能");
}
项目:UaicNlpToolkit    文件:PrecompileFromDexOnlineDB.java   
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException, SQLException {
    Class.forName("com.mysql.jdbc.Driver");

    Connection con = DriverManager.getConnection("jdbc:mysql://localhost/dexonline?useUnicode=true&characterEncoding=UTF-8", "dexro", "dexro");

    System.out.println("uncomment lines in main!");

    updateVerbs(con);
    updateNounsCommon(con);
    updateNounsPers(con);
    updateAdjs(con);
    updateAdjsInvar(con);
    updateAdvs(con);
    updatePreps(con);
    updateDemPronouns(con);
    updateIndefPronouns(con);
    updatePersPronouns(con);
    updateNegPronouns(con);
    updatePosPronouns(con);
    updateReflPronouns(con);
    updateRelPronouns(con);
    updateDemDets(con);
    updateArticles(con);
    updateConjs(con);
    updateInterjs(con);
    updateNumOrd(con);
    updateNumCard(con);
    updateNumCol(con);
    updateLexemPriority(con);
}
项目:Sensors    文件:DBConnection.java   
public DBConnection (){
    try {
        this.conn= DriverManager.getConnection(JDBC_URL);

        if (this.conn!= null ){
        //  System.out.println("Connected to DB");
        }
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

}
项目:Hydrograph    文件:DataViewerAdapter.java   
private void createConnection() throws ClassNotFoundException, SQLException, IOException {
    Class.forName(AdapterConstants.CSV_DRIVER_CLASS);
    Properties properties = new Properties();
    properties.put(AdapterConstants.COLUMN_TYPES, getType(databaseName).replaceAll(AdapterConstants.DATE,AdapterConstants.TIMESTAMP));
    connection = DriverManager.getConnection(AdapterConstants.CSV_DRIVER_CONNECTION_PREFIX + databaseName,properties);
    statement = connection.createStatement();
}
项目:parabuild-ci    文件:JDBCBench.java   
public static Connection connect(String DBUrl, String DBUser,
                                 String DBPassword) {

    try {
        Connection conn = DriverManager.getConnection(DBUrl, DBUser,
            DBPassword);

        return conn;
    } catch (Exception E) {
        System.out.println(E.getMessage());
        E.printStackTrace();
    }

    return null;
}