Java Code Examples for java.sql.DriverManager

The following are top voted examples for showing how to use java.sql.DriverManager. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: otus_java_2017_04   File: ConnectionHelper.java   Source Code and License 9 votes vote down vote up
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);
    }
}
 
Example 2
Project: Roaster-Management-Application   File: Register.java   Source Code and License 8 votes vote down vote up
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;
	
}
 
Example 3
Project: MybatisGeneatorUtil   File: SqlScriptRunner.java   Source Code and License 7 votes vote down vote up
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);
        }
    }
 
Example 4
Project: uavstack   File: JdbcDriverIT.java   Source Code and License 6 votes vote down vote up
/**
 * 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;

}
 
Example 5
Project: AlphaLibary   File: SQLiteAPI.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
        }
    }
}
 
Example 6
Project: QDrill   File: TestJdbcDistQuery.java   Source Code and License 6 votes vote down vote up
@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);
  }
}
 
Example 7
Project: big_data   File: JdbcManager.java   Source Code and License 6 votes vote down vote up
/**
 * 根据配置获取获取关系型数据库的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");
}
 
Example 8
Project: Course-Management-System   File: StudentCourseOutlineDAO.java   Source Code and License 6 votes vote down vote up
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);
	}
}
 
Example 9
Project: Equella   File: DatabaseConnectCallback.java   Source Code and License 6 votes vote down vote up
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();
		}
	}
}
 
Example 10
Project: calcite-avatica   File: RemoteMetaTest.java   Source Code and License 6 votes vote down vote up
@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());
  }
}
 
Example 11
Project: calcite-avatica   File: RemoteMetaTest.java   Source Code and License 6 votes vote down vote up
@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();
  }
}
 
Example 12
Project: elastic-db-tools-for-java   File: SqlDatabaseUtils.java   Source Code and License 6 votes vote down vote up
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();
    }
}
 
Example 13
Project: elastic-db-tools-for-java   File: ShardMapManagerTests.java   Source Code and License 6 votes vote down vote up
/**
 * 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();
        }
    }
}
 
Example 14
Project: AlphaLibary   File: MySQLConnector.java   Source Code and License 6 votes vote down vote up
@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;
        }
    }
}
 
Example 15
Project: dev-courses   File: TestSqlPersistent.java   Source Code and License 6 votes vote down vote up
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());
        }
    }
 
Example 16
Project: incubator-netbeans   File: MetadataElementHandleTest.java   Source Code and License 6 votes vote down vote up
@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();
}
 
Example 17
Project: incubator-netbeans   File: JDBCMetadataDerbyTest.java   Source Code and License 6 votes vote down vote up
@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");
}
 
Example 18
Project: incubator-netbeans   File: DbDriverManagerTest.java   Source Code and License 6 votes vote down vote up
/**
 * 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);
    }
}
 
Example 19
Project: elastic-db-tools-for-java   File: ShardMapManagerLoadTests.java   Source Code and License 6 votes vote down vote up
/**
 * 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()));
        }
    }
}
 
Example 20
Project: mountieLibrary   File: MountieQueries.java   Source Code and License 6 votes vote down vote up
/**
 * 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);
    } 
}
 
Example 21
Project: quorrabot   File: SqliteStore.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 22
Project: PetBlocks   File: DatabaseIT.java   Source Code and License 6 votes vote down vote up
@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();
    }
}
 
Example 23
Project: Transwarp-Sample-Code   File: Connector.java   Source Code and License 6 votes vote down vote up
/**
 * 创建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;
}
 
Example 24
Project: SkyWarsReloaded   File: Database.java   Source Code and License 6 votes vote down vote up
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);
    }
}
 
Example 25
Project: mczone   File: MySQL.java   Source Code and License 6 votes vote down vote up
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;
}
 
Example 26
Project: endpoint-health   File: EndPointHealthServiceImpl.java   Source Code and License 6 votes vote down vote up
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);
    }
}
 
Example 27
Project: docker-compose-rule-with-junit5   File: SimpleTest.java   Source Code and License 6 votes vote down vote up
@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);
}
 
Example 28
Project: sstore-soft   File: JavaSystem.java   Source Code and License 6 votes vote down vote up
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
    }
 
Example 29
Project: mdw-demo   File: MariaDBEmbeddedDb.java   Source Code and License 6 votes vote down vote up
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();
    }
}
 
Example 30
Project: nh-micro   File: MicroXaDataSource.java   Source Code and License 6 votes vote down vote up
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;
    }
 
Example 31
Project: AlphaLibary   File: MySQLAPI.java   Source Code and License 6 votes vote down vote up
/**
 * 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;
        }
    }
}
 
Example 32
Project: s-store   File: TestJDBCDriver.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 33
Project: calcite-avatica   File: AlternatingRemoteMetaTest.java   Source Code and License 5 votes vote down vote up
@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();
  }
}
 
Example 34
Project: OrthancAnonymization   File: JDBCConnector.java   Source Code and License 5 votes vote down vote up
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));
	}
}
 
Example 35
Project: openjdk-jdk10   File: DriverManagerModuleTests.java   Source Code and License 5 votes vote down vote up
/**
 * 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();

}
 
Example 36
Project: ArchersBattle   File: Main.java   Source Code and License 5 votes vote down vote up
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() + "个技能");
}
 
Example 37
Project: UaicNlpToolkit   File: PrecompileFromDexOnlineDB.java   Source Code and License 5 votes vote down vote up
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);
}
 
Example 38
Project: Sensors   File: DBConnection.java   Source Code and License 5 votes vote down vote up
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();
	}
	
}
 
Example 39
Project: Hydrograph   File: DataViewerAdapter.java   Source Code and License 5 votes vote down vote up
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();
}
 
Example 40
Project: parabuild-ci   File: JDBCBench.java   Source Code and License 5 votes vote down vote up
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;
}
 
Example 41
Project: spring2017java   File: FXMLDocumentController.java   Source Code and License 5 votes vote down vote up
@Override
public void initialize(URL url, ResourceBundle rb) {
    studentsList = FXCollections.observableArrayList();
    studentsListView.setItems(studentsList);
    studentsTableView.setItems(studentsList);
    
    // lambda expression
    nameColumn.setCellValueFactory(data -> new SimpleStringProperty(data.getValue().getStudentName()));
    idColumn.setCellValueFactory(data -> new SimpleIntegerProperty(data.getValue().getStudentId()));
    cgpaColumn.setCellValueFactory(data -> new SimpleDoubleProperty(data.getValue().getCgpa()));
    
    try {
        Connection connection = DriverManager
                .getConnection("jdbc:mysql://172.17.0.119/spring2017db",
                        "javauser",
                        "java");
        Statement statement = connection.createStatement();
        String query = "SELECT * FROM student";

        ResultSet resultSet = statement.executeQuery(query);
        int rows = 0;
        while (resultSet.next()) {
            int id = resultSet.getInt("studentId");
            String name = resultSet.getString("studentName");
            double cgpa = resultSet.getDouble("cgpa");
            Student student = new Student(id, name, cgpa);
            studentsList.add(student);
            rows++;
        }
        statusLabel.setText("Successfully loaded " + rows + " records from the database");
    } catch (SQLException sqle) {
        Alert alert = new Alert(AlertType.ERROR);
        alert.setTitle("Error Message");
        alert.setContentText("Could not connect to the database");
        alert.showAndWait();
        System.exit(0);
        System.err.println("Could not connect to the database");
    }
}
 
Example 42
Project: brooklyn   File: Application.java   Source Code and License 5 votes vote down vote up
private static void initDatabase(String dbUri) {
    try {
        Application.database = DriverManager.getConnection(dbUri);
        MessagesModel.init(Application.database);
    } catch (SQLException e) {
        logger.error("Failed loading the database. ", e);
    }
}
 
Example 43
Project: the-vigilantes   File: UI.java   Source Code and License 5 votes vote down vote up
public void showTableData(){
    try{
        con = DriverManager.getConnection("jdbc:mysql://localhost:3306/slit?autoReconnect=true&useSSL=false","root","root");
        String sql = "SELECT * FROM user";
        pst = con.prepareStatement(sql);
        rs=pst.executeQuery();
        jTable1.setModel(DbUtils.resultSetToTableModel(rs));
}
    catch(Exception ex){
        JOptionPane.showMessageDialog(null, ex);
        
    }


}
 
Example 44
Project: spr   File: SqlHelper.java   Source Code and License 5 votes vote down vote up
public static Connection conectar(){/*
	 Connection con = null;
        Statement st = null;
        ResultSet rs = null;
        //try {Class.forName("com.mysql.jdbc.Driver");}
        try {Class.forName("org.postgresql.Driver");}
        catch (ClassNotFoundException e) {e.printStackTrace();}
        String url = "";

        //String user = "root";
        String user = "postgres";
        String password = "postgres";

        //try {con = DriverManager.getConnection("jdbc:mysql://mysql01.stp.gov.py/spr", "root", "postgres");}
        try {con = DriverManager.getConnection("jdbc:postgresql://pg01.stp.gov.py/spr", "postgres", "postgres");}
        catch (SQLException ex) {
            Logger lgr = Logger.getLogger(SqlHelper.class.getName());
            lgr.log(Level.SEVERE, ex.getMessage(), ex);
        } 
        return con;*/
	Connection con = null;
    Statement st = null;
    ResultSet rs = null;
    try {Class.forName("org.postgresql.Driver");}
    catch (ClassNotFoundException e) {e.printStackTrace();}
    String url = "";
    String user = "postgres";
    String password = "postgres";

    try {con = DriverManager.getConnection("jdbc:postgresql://pg01.stp.gov.py/spr?useUnicode=true&characterEncoding=UTF-8&user=postgres&password=postgres");}
    catch (SQLException ex) {
        Logger lgr = Logger.getLogger(SqlHelper.class.getName());
        lgr.log(Level.SEVERE, ex.getMessage(), ex);
    } 
    return con;
}
 
Example 45
Project: ant-config-server   File: SqliteJdbc.java   Source Code and License 5 votes vote down vote up
@Override
public void processor(Blade blade) {
    try {

        DB_PATH = Const.CLASSPATH + File.separatorChar + DB_NAME;
        DB_SRC = "jdbc:sqlite://" + DB_PATH;

        DB_PATH = System.getProperty("user.dir") + "/" + DB_NAME;
        DB_SRC = "jdbc:sqlite://" + DB_PATH;

        log.info("load sqlite database path [{}]", DB_PATH);
        log.info("load sqlite database src [{}]", DB_SRC);

        Connection con       = DriverManager.getConnection(DB_SRC);
        Statement statement = con.createStatement();
        ResultSet rs        = statement.executeQuery("SELECT count(*) FROM sqlite_master WHERE type='table' AND name='t_config_service'");
        int        count     = rs.getInt(1);
        if (count == 0) {
            String            cp  = SqliteJdbc.class.getClassLoader().getResource("").getPath();
            InputStreamReader isr = new InputStreamReader(new FileInputStream(cp + "schema.sql"), "UTF-8");

            String sql = new BufferedReader(isr).lines().collect(Collectors.joining("\n"));
            int    r   = statement.executeUpdate(sql);
            log.info("initialize import database - {}", r);
        }
        rs.close();
        statement.close();
        con.close();
        log.info("database path is: {}", DB_PATH);
    } catch (Exception e) {
        log.error("initialize database fail", e);
    }
}
 
Example 46
Project: morpheus-core   File: DbSourceOptions.java   Source Code and License 5 votes vote down vote up
/**
 * Sets the JDBC connection URL and optional credentials
 * This method should ideally only be used for testing, a connection pool is preferable for production
 * @param url       the JDBC connection url
 * @param username  the JDBC connection username, can be null
 * @param password  the JDBC connection password, can be null
 * @return          this request
 */
public DbSourceOptions<R> withConnection(String url, String username, String password) {
    try {
        Objects.requireNonNull(url, "The JDBC URL cannnot be null");
        this.connection = DriverManager.getConnection(url, username, password);
        return this;
    } catch (SQLException ex) {
        throw new DataFrameException("Failed to create connection for URL:" + url, ex);
    }
}
 
Example 47
Project: sc-generator   File: GeneratorController.java   Source Code and License 5 votes vote down vote up
@RequestMapping(value = "/executeSql", method = RequestMethod.POST)
public void executeSql(MultipartFile file, HttpServletResponse response) throws SQLException, IOException {
    Connection connection = DriverManager.getConnection(url + "mysql", username, password);
    String db = ("SC" + UUID.randomUUID().toString().substring(0, 5)).toLowerCase();
    List<String> sqls = Arrays.asList("CREATE DATABASE IF NOT EXISTS " + db + " DEFAULT CHARSET utf8",
            "CREATE USER '" + db + "'@'%' IDENTIFIED BY '" + db + "'",
            "grant all privileges on " + db + ".* to '" + db + "'@'%' identified by '" + db + "'");
    for (String sql : sqls) {
        Statement statement = connection.createStatement();
        statement.execute(sql);
        statement.close();
    }

    connection.close();

    String jdbcUrl = url + db;
    connection = DriverManager.getConnection(url, db, db);
    ScriptUtils.executeSqlScript(connection, new InputStreamResource(file.getInputStream()));
    connection.close();

    datasourceService.save(new Datasource()
            .setJdbcUrl(jdbcUrl)
            .setName(file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf(".")))
            .setUsername(db)
            .setPassword(db)
            .setDriver("com.mysql.jdbc.Driver"));
    response.sendRedirect("/");
}
 
Example 48
Project: openjdk-jdk10   File: DriverManagerTests.java   Source Code and License 5 votes vote down vote up
/**
 * Validate that a non-null Driver is returned by getDriver when a valid URL
 * is specified
 */
@Test
public void test12() throws Exception {

    DriverManager.registerDriver(new StubDriver());
    assertTrue(DriverManager.getDriver(StubDriverURL) != null);
}
 
Example 49
Project: Machine-Learning-End-to-Endguide-for-Java-developers   File: DatabaseExample.java   Source Code and License 5 votes vote down vote up
public DatabaseExample() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            String url = "jdbc:mysql://localhost:3306/example";
            connection = DriverManager.getConnection(url, "root", "explore");

            // Needed to reset the contents of the table
            Statement statement = connection.createStatement();
            statement.execute("TRUNCATE URLTABLE;");
            
            String insertSQL = "INSERT INTO  `example`.`URLTABLE` "
                    + "(`url`) VALUES " + "(?);";
            PreparedStatement stmt = connection.prepareStatement(insertSQL);
            
            stmt.setString(1, "https://en.wikipedia.org/wiki/Data_science");
            stmt.execute();
            stmt.setString(1, "https://en.wikipedia.org/wiki/Bishop_Rock,_Isles_of_Scilly");
            stmt.execute();

//            String selectSQL = "select * from Record where URL = '" + url + "'";
            String selectSQL = "select * from URLTABLE";
            statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery(selectSQL);
            
            out.println("List of URLs");
            while (resultSet.next()) {
                out.println(resultSet.getString(2));
            } 
        } catch (SQLException | ClassNotFoundException ex) {
            ex.printStackTrace();
        }
    }
 
Example 50
Project: zencash-swing-wallet-ui   File: ArizenWallet.java   Source Code and License 5 votes vote down vote up
@Override
public void createWallet(File f) throws Exception {					
		String url = "jdbc:sqlite:" + f.getAbsolutePath();
		conn = DriverManager.getConnection(url);
		Statement stmt = conn.createStatement();
		String sqlWallet = "CREATE TABLE wallet " + "(id INTEGER PRIMARY KEY AUTOINCREMENT, pk TEXT, addr TEXT UNIQUE, lastbalance REAL, name TEXT);";
		stmt.execute(sqlWallet);
		String sqlZWallet = "CREATE TABLE zwallet " + "(id INTEGER PRIMARY KEY AUTOINCREMENT, pk TEXT, spk TEXT, addr TEXT UNIQUE, lastbalance REAL, name TEXT);";
		stmt.execute(sqlZWallet);
		
		String sqlContacts = "CREATE TABLE contacts (id INTEGER PRIMARY KEY AUTOINCREMENT, addr TEXT UNIQUE, name TEXT, nick TEXT);";
		stmt.execute(sqlContacts);
		String sqlSettings = "CREATE TABLE settings (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT UNIQUE, value TEXT);";
		stmt.execute(sqlSettings);
		String sqlTransactions = "CREATE TABLE transactions (id INTEGER PRIMARY KEY AUTOINCREMENT, txid TEXT, time INTEGER, address TEXT, vins TEXT, vouts TEXT, amount REAL, block INTEGER);";
		stmt.execute(sqlTransactions);
		
		String st1 = "INSERT INTO settings(name, value) VALUES (?, ?)"; 
		PreparedStatement pstmt = conn.prepareStatement(st1);
		pstmt.setString(1, "settingsExplorer");
		pstmt.setString(2, settingExplorer);
		pstmt.execute();

		pstmt.setString(1, "settingsNotifications");
		pstmt.setString(2, settingNotification);
		pstmt.execute();

		pstmt.setString(1, "settingsApi");
		pstmt.setString(2, settingApi);
		pstmt.execute();
		
}
 
Example 51
Project: Java-9-Cookbook   File: Chapter06Database02.java   Source Code and License 5 votes vote down vote up
private static Connection getDbConnection1(){
    String url = "jdbc:postgresql://localhost/cookbook";
    Properties prop = new Properties( );
    //prop.put( "user", "cook" );
    //prop.put( "password", "secretPass123" );

    try {
        return DriverManager.getConnection(url, prop);
    }
    catch(Exception ex) {
        ex.printStackTrace();
        return null;
    }
}
 
Example 52
Project: TestDemo1-github   File: ConnectDB.java   Source Code and License 5 votes vote down vote up
private static Connection getMySqlConn(String url, String user,
		String password) throws SQLException {
	Connection conn = null;
	try {
		Class.forName("com.mysql.jdbc.Driver");// 加载驱动
	} catch (ClassNotFoundException e) {
		e.printStackTrace();
	}
	conn = DriverManager.getConnection(MYSQL + url, "root", "root");

	return conn;
}
 
Example 53
Project: openjdk-jdk10   File: DriverManagerTests.java   Source Code and License 5 votes vote down vote up
/**
 * Utility method to see if a driver is registered
 */
private boolean isDriverRegistered(Driver d) {
    boolean foundDriver = false;
    java.util.Enumeration e = DriverManager.getDrivers();
    while (e.hasMoreElements()) {
        if (d == (Driver) e.nextElement()) {
            foundDriver = true;
            break;
        }
    }
    return foundDriver;
}
 
Example 54
Project: Notebook   File: DBHelper.java   Source Code and License 5 votes vote down vote up
/** ��ȡ���� */
  private static Connection getConnection(){
  	try {
  		Connection connection = DriverManager.getConnection("jdbc:sqlite:" + DB_NAME);//����Ҫ�û��� ����    jdbc:mysql://localhost:3306/test,û��test.db����Զ������ļ�
  		return connection;
} catch (Exception e) {
	e.printStackTrace();
}
  	return null;
  }
 
Example 55
Project: weixin_api   File: DbStorage.java   Source Code and License 5 votes vote down vote up
@Override
public <T> T get(String key, Class<T> type) {
	T value = null;
	try {
		byte[] bytes = null;
		Connection conn = null;
		try {
			conn = DriverManager.getConnection(dbAlias);
			PreparedStatement pst = conn
					.prepareStatement(String.format("SELECT %s FROM %s WHERE %s=?", fieldValue, table, fieldKey));
			pst.setString(1, key);
			ResultSet rs = pst.executeQuery();

			if (rs.next()) {
				bytes = rs.getBytes(1);
			}
			rs.close();
			pst.close();
		} finally {
			if (conn != null) {
				conn.close();
			}
		}
		Object obj = bytes2object(bytes);
		if (obj != null) {
			value = type.cast(obj);
		}
	} catch (Exception e) {
		log.error(String.format("键值获取失败 %s", key), e);
	}
	return value;
}
 
Example 56
Project: spring2017java   File: FXMLDocumentController.java   Source Code and License 5 votes vote down vote up
@FXML
private void handleAddStudentAction(ActionEvent event) {
    int studentId = 0;
    try {
        studentId = Integer.parseInt(studentIdField.getText());
    } catch (NumberFormatException nfe) {
        Alert alert = new Alert(AlertType.ERROR);
        alert.setTitle("Error Message");
        alert.setHeaderText("Incorrect student Id");
        alert.setContentText("Student Id has to be an integer in the range[1, 1000]");
        alert.showAndWait();
        return;
    }
    String studentName = studentNameField.getText();
    double cgpa = Double.parseDouble(cgpaField.getText());

    try {
        Connection connection = DriverManager
                .getConnection("jdbc:mysql://172.17.0.119/spring2017db",
                        "javauser",
                        "java");
        Statement statement = connection.createStatement();
        String query = "INSERT INTO student VALUES(" + studentId
                + ", '" + studentName + "', " + cgpa + ")";
        System.out.println(query);
        statement.executeUpdate(query);
        Student student = new Student(studentId, studentName, cgpa);
        studentsList.add(student);
        statusLabel.setText("Added a new entry for " + studentName);
        studentIdField.clear();
        studentNameField.clear();
        cgpaField.clear();
    } catch (SQLException sqle) {

    }

}
 
Example 57
Project: the-vigilantes   File: UI.java   Source Code and License 5 votes vote down vote up
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
    try{
        String sql = "INSERT INTO user"
        +"(user_id, user_fname, user_lname, user_password, user_email, user_status, user_m1, user_m2, user_m3, user_m4, user_m5)"
        +"VALUES (?,?,?,?,?,?,?,?,?,?,?)";
        con = DriverManager.getConnection("jdbc:mysql://localhost:3306/slit?autoReconnect=true&useSSL=false","root","root");
        pst = con.prepareStatement(sql);
        pst.setString(1,id.getText());
        pst.setString(2,fornavn.getText());
        pst.setString(3,etternavn.getText());
        pst.setString(4,password.getText());
        pst.setString(5,epost.getText());
        pst.setString(6,status.getText());
        pst.setString(7,modul1.getText());
        pst.setString(8,modul2.getText());
        pst.setString(9,modul3.getText());
        pst.setString(10,modul4.getText());
        pst.setString(11,modul5.getText());
        pst.executeUpdate();
        JOptionPane.showMessageDialog(null, "inserted successfully");

    }
    catch(SQLException | HeadlessException ex){
        JOptionPane.showMessageDialog(null, ex);
    }
    showTableData();
}
 
Example 58
Project: wherehowsX   File: AzLogParserTest.java   Source Code and License 5 votes vote down vote up
@BeforeTest
public void setUp()
  throws SQLException {
  Properties prop = new LineageTest().properties;

  String wherehowsHost = prop.getProperty(Constant.WH_DB_URL_KEY);
  String wherehowsUserName = prop.getProperty(Constant.WH_DB_USERNAME_KEY);
  String wherehowsPassWord = prop.getProperty(Constant.WH_DB_PASSWORD_KEY);
  Connection conn =
    DriverManager.getConnection(wherehowsHost + "?" + "user=" + wherehowsUserName + "&password=" + wherehowsPassWord);
  AzLogParser.initialize(conn);
}
 
Example 59
Project: BibliotecaPS   File: FabricMultiTenantConnectionProvider.java   Source Code and License 5 votes vote down vote up
/**
 * Find a server with mode READ_WRITE in the given server group and create a JDBC connection to it.
 * 
 * @returns a {@link Connection} to an arbitrary MySQL server
 * @throws SQLException
 *             if connection fails or a READ_WRITE server is not contained in the group
 */
private Connection getReadWriteConnectionFromServerGroup(ServerGroup serverGroup) throws SQLException {
    for (Server s : serverGroup.getServers()) {
        if (ServerMode.READ_WRITE.equals(s.getMode())) {
            String jdbcUrl = String.format("jdbc:mysql://%s:%s/%s", s.getHostname(), s.getPort(), this.database);
            return DriverManager.getConnection(jdbcUrl, this.user, this.password);
        }
    }
    throw new SQLException("Unable to find r/w server for chosen shard mapping in group " + serverGroup.getName());
}
 
Example 60
Project: reactive-pg-client   File: JdbcTestBase.java   Source Code and License 5 votes vote down vote up
@Before
public void setUp() throws Exception {
  Properties props = new Properties();
  PGProperty.PREPARE_THRESHOLD.set(props, -1);
  PGProperty.BINARY_TRANSFER.set(props, "true");
  // PGProperty.BINARY_TRANSFER_ENABLE.set(props, "true");
  PGProperty.USER.set(props, "postgres");
  PGProperty.PASSWORD.set(props, "postgres");
  con = DriverManager.getConnection("jdbc:postgresql://"
    + options.getHost() + ":"
    + options.getPort() + "/postgres", props);

}