微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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");
}
项目: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.get@R_874_4045@ion().getDatabaseName());
    } else {
        try {
            handler.disconnect();

            Connection c = DriverManager.getConnection(
                    "jdbc:MysqL://" + handler.get@R_874_4045@ion().getHost() + ":" + handler.get@R_874_4045@ion().getPort() + "/" + handler.get@R_874_4045@ion().getDatabaseName() + "?autoReconnect=true",handler.get@R_874_4045@ion().getUserName(),handler.get@R_874_4045@ion().getpassword());

            sqlConnectionHandler.getConnectionMap().put(handler.get@R_874_4045@ion().getDatabaseName(),c);

            return c;
        } catch (sqlException ignore) {
            Bukkit.getLogger().log(Level.WARNING,"Failed to connect to " + handler.get@R_874_4045@ion().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,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,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,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",password);

            CONNECTIONS.put(database,"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",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,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;
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。