Java Code Examples for java.sql.Driver#connect()

The following examples show how to use java.sql.Driver#connect() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Dialect.java    From MogwaiERDesignerNG with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Create a connection to a database.
 *
 * @param aClassLoader	   the classloader
 * @param aDriver			the name of the driver
 * @param aUrl			   the url
 * @param aUser			  the user
 * @param aPassword		  the password
 * @param aPromptForPassword shall be prompted for the password
 * @return the connection
 * @throws ClassNotFoundException is thrown in case of an error
 * @throws InstantiationException is thrown in case of an error
 * @throws IllegalAccessException is thrown in case of an error
 * @throws SQLException		   is thrown in case of an error
 */
public Connection createConnection(ClassLoader aClassLoader, String aDriver, String aUrl, String aUser, String aPassword, boolean aPromptForPassword) throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {
	Class<Driver> theDriverClass = (Class<Driver>) aClassLoader.loadClass(aDriver);
	Driver theDriver = theDriverClass.newInstance();

	if (aPromptForPassword) {
		aPassword = DialogUtils.promptForPassword();
		if (aPassword == null) {
			return null;
		}
	}

	Properties theProperties = new Properties();
	theProperties.put("user", aUser);
	theProperties.put("password", aPassword);

	return theDriver.connect(aUrl, theProperties);
}
 
Example 2
Source File: DriverTest.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
/**
 * Do java.sql.Driver.connect(String url, Properties info call)
 *
 * @param expectUrlEqualsGetUrl boolean indicating embedded would
 *                  expect the url passed in to equal metadata.getURL()
 * @param url       url to pass to Driver.connect()
 * @param info      properties to pass to Driver.Connect()
 *
 * @throws SQLException on error.
 */
private static void assertConnect(
    boolean expectUrlEqualsGetUrl, String url, Properties info)
throws SQLException
{
    Driver driver = DriverManager.getDriver(url);

    Connection conn = driver.connect(url, info);
    assertNotNull(conn);

    if (expectUrlEqualsGetUrl)
        assertEquals(url, conn.getMetaData().getURL());
    else
        assertNotSame(url, conn.getMetaData().getURL());
    ResultSet rs =
        conn.createStatement().executeQuery("VALUES(CURRENT SCHEMA)");
    rs.next();
    assertEquals(
        rs.getString(1), conn.getMetaData().getUserName().toUpperCase());
    rs.close();
    conn.close();
    return;
}
 
Example 3
Source File: DefaultPersistManager.java    From onedev with MIT License 6 votes vote down vote up
protected Connection getConnection() {
	try {
		Driver driver = (Driver) Class.forName(properties.getDriver(), true, 
				Thread.currentThread().getContextClassLoader()).newInstance();
		Properties connectProps = new Properties();
		String user = properties.getUser();
		String password = properties.getPassword();
        if (user != null) 
            connectProps.put("user", user);
        if (password != null) 
            connectProps.put("password", password);
		
		return driver.connect(properties.getUrl(), connectProps);
	} catch (Exception e) {
		throw ExceptionUtils.unchecked(e);
	}
}
 
Example 4
Source File: DBSetting.java    From ermasterr with Apache License 2.0 6 votes vote down vote up
public Connection connect() throws InputException, InstantiationException, IllegalAccessException, SQLException {
    final DBManager manager = DBManagerFactory.getDBManager(getDbsystem());
    final Class<Driver> driverClass = manager.getDriverClass(getDriverClassName());

    if (driverClass == null) {
        throw new InputException("error.jdbc.driver.not.found");
    }

    final Driver driver = driverClass.newInstance();

    final Properties info = new Properties();
    if (getUser() != null) {
        info.put("user", getUser());
    }
    if (getPassword() != null) {
        info.put("password", getPassword());
    }

    return driver.connect(getUrl(), info);
}
 
Example 5
Source File: ConnectionFactory.java    From query2report with GNU General Public License v3.0 5 votes vote down vote up
public static boolean testConnection(ConnectionParams params) throws Exception {
	boolean status = false;
	String url = params.getUrl();
	DriverParams driverParams = DriverManager.getDriverManager().getDriver(params.getDriver());
	String driverClass = driverParams.getClassName();
	String username = params.getUsername();
	String password = params.getPassword();
	String decPassword = EncryptionUtil.decrypt(password);
	logger.info("Trying to get connection to DB " + url + " for user " + username + " and driver class [" + driverClass + "]");
	try{
		Driver driver = (Driver) Class.forName(driverClass).newInstance();
		Properties props = new Properties();
		props.put("user", username);
		props.put("password", decPassword);
		if(driver.acceptsURL(url)){
			Connection connection = driver.connect(url, props);
			connection.setAutoCommit(false);
			logger.info("Got new connection to DB " + url + " for user " + username);
			status=true;
			params.setIsConnectionSuccess(Boolean.toString(status));
			connection.close();
		}else{
			logger.error("Driver "+params.getDriver()+" is not suitable for URL "+url);
			throw new RuntimeException("Driver "+params.getDriver()+" is not suitable for URL "+url);
		}
	}catch (Throwable e){
		logger.error("Error getting connection to "+url+" for user "+username,e);
		throw e;
	}
	return status;
}
 
Example 6
Source File: DriverProxyInvocationChainTest.java    From pentaho-hadoop-shims with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetTablesWithSchema() throws SQLException {
  Class hive2;
  try {
    hive2 = Class.forName( "org.apache.hive.jdbc.HiveDatabaseMetaData" );
  } catch ( ClassNotFoundException e ) {
    return;
  }
  if ( hive2 != null ) {
    Driver driverMock = mock( HiveDriver.class );
    Driver driverProxy = DriverProxyInvocationChain.getProxy( Driver.class, driverMock );

    Connection connectionMock = mock( Connection.class );
    doReturn( connectionMock ).when( driverMock ).connect( anyString(), (Properties) isNull() );

    Statement statementMock = mock( Statement.class );
    doReturn( statementMock ).when( connectionMock ).createStatement();

    ResultSet resultSet = mock( ResultSet.class );
    doReturn( resultSet ).when( statementMock ).executeQuery( anyString() );

    DatabaseMetaData databaseMetaDataMock = (DatabaseMetaData) mock( hive2 );
    doReturn( databaseMetaDataMock ).when( connectionMock ).getMetaData();

    String schema = "someSchema";
    doThrow( new SQLException( "Method is not supported" ) ).when( databaseMetaDataMock )
      .getTables( null, schema, null, null );

    Connection conn = driverProxy.connect( "jdbc:hive://host:port/dbName", null );

    conn.getMetaData().getTables( null, schema, null, null );
    verify( statementMock ).execute( "use dbName" );
    verify( statementMock ).executeQuery( "show tables in " + schema );
  }
}
 
Example 7
Source File: SimpleDriverDataSource.java    From spring4-understanding with Apache License 2.0 5 votes vote down vote up
@Override
protected Connection getConnectionFromDriver(Properties props) throws SQLException {
	Driver driver = getDriver();
	String url = getUrl();
	Assert.notNull(driver, "Driver must not be null");
	if (logger.isDebugEnabled()) {
		logger.debug("Creating new JDBC Driver Connection to [" + url + "]");
	}
	return driver.connect(url, props);
}
 
Example 8
Source File: SlaveDatabase.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
     * Used to shutdown this database. 
     *
     * If an error occurs as part of the database boot process, we
     * hand the exception that caused boot to fail to the client
     * thread. The client thread will in turn shut down this database.
     *
     * If an error occurs at a later stage than during boot, we shut
     * down the database by setting up a connection with the shutdown
     * attribute. The internal connection is required because database
     * shutdown requires EmbedConnection to do cleanup.
     *
     * @param shutdownCause the reason why the database needs to be
     * shutdown
     */
    private void handleShutdown(StandardException shutdownCause) {
        if (inBoot) {
            bootException = shutdownCause;
            return;
        } 
        try {
            shutdownInitiated = true;
            String driverName = 
                "com.pivotal.gemfirexd.jdbc.EmbeddedDriver";

            Class.forName(driverName).newInstance();

            Driver embedDriver = 
                DriverManager.getDriver(com.pivotal.gemfirexd.Attribute.PROTOCOL);

// GemStone changes BEGIN
            String conStr = com.pivotal.gemfirexd.Attribute.PROTOCOL + ";" +
            /* String conStr = "jdbc:derby:"+dbname+";"+ */
// GemStone changes END
                Attribute.REPLICATION_INTERNAL_SHUTDOWN_SLAVE+
                "=true";

            embedDriver.connect(conStr, (Properties) null);
        } catch (Exception e) {
            // Todo: report error to gemfirexd.log if exception is not
            // SQLState.SHUTDOWN_DATABASE
        }
    }
 
Example 9
Source File: SimpleDriverDataSource.java    From effectivejava with Apache License 2.0 5 votes vote down vote up
@Override
protected Connection getConnectionFromDriver(Properties props) throws SQLException {
	Driver driver = getDriver();
	String url = getUrl();
	Assert.notNull(driver, "Driver must not be null");
	if (logger.isDebugEnabled()) {
		logger.debug("Creating new JDBC Driver Connection to [" + url + "]");
	}
	return driver.connect(url, props);
}
 
Example 10
Source File: QueryTest.java    From sql-maven-plugin with Apache License 2.0 5 votes vote down vote up
public void testQuery()
    throws Exception
{
    Class dc = Class.forName( "org.apache.derby.jdbc.EmbeddedDriver" );
    Driver   driverInstance = (Driver) dc.newInstance();

    Connection conn = driverInstance.connect( "jdbc:derby:target/testdb", null );

    Statement st = conn.createStatement();
    ResultSet rs = st.executeQuery( "select count(*) from derbyDB" );
    rs.next();
    assertEquals( 2, rs.getInt(1) );  
    
}
 
Example 11
Source File: DriverTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
/**
 * use this method to shutdown databases in an effort to release
 * any locks they may be holding
 */
private static void shutdownDB(String url, Properties info) throws SQLException {

    Driver driver = DriverManager.getDriver(url);
    try {
        driver.connect(url, info);
    } catch (SQLException se) {
        assertSQLState("08006", se);
    }
}
 
Example 12
Source File: DriverTest.java    From spliceengine with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * use this method to shutdown databases in an effort to release
 * any locks they may be holding
 */
private static void shutdownDB(String url, Properties info) throws SQLException {

    Driver driver = DriverManager.getDriver(url);
    try {
        driver.connect(url, info);
    } catch (SQLException se) {
        assertSQLState("08006", se);
    }
}
 
Example 13
Source File: PhoenixDriverTest.java    From phoenix with Apache License 2.0 5 votes vote down vote up
@Test
public void testFirstConnectionWhenUrlHasTenantId() throws Exception {
    final String tenantId = "00Dxx0000001234";
    String url = getUrl() + ";" + PhoenixRuntime.TENANT_ID_ATTRIB + "=" + tenantId;
    Driver driver = new PhoenixTestDriver();

    driver.connect(url, new Properties());
}
 
Example 14
Source File: JpaTransactionManagerRule.java    From nomulus with Apache License 2.0 5 votes vote down vote up
private static Connection createConnection() {
  final Properties info = new Properties();
  info.put("user", database.getUsername());
  info.put("password", database.getPassword());
  final Driver jdbcDriverInstance = database.getJdbcDriverInstance();
  try {
    return jdbcDriverInstance.connect(getJdbcUrl(), info);
  } catch (SQLException e) {
    throw new RuntimeException(e);
  }
}
 
Example 15
Source File: UtilHelpers.java    From hudi with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a factory for creating connections to the given JDBC URL.
 *
 * @param options - JDBC options that contains url, table and other information.
 * @return
 * @throws SQLException if the driver could not open a JDBC connection.
 */
private static Connection createConnectionFactory(Map<String, String> options) throws SQLException {
  String driverClass = options.get(JDBCOptions.JDBC_DRIVER_CLASS());
  DriverRegistry.register(driverClass);
  Enumeration<Driver> drivers = DriverManager.getDrivers();
  Driver driver = null;
  while (drivers.hasMoreElements()) {
    Driver d = drivers.nextElement();
    if (d instanceof DriverWrapper) {
      if (((DriverWrapper) d).wrapped().getClass().getCanonicalName().equals(driverClass)) {
        driver = d;
      }
    } else if (d.getClass().getCanonicalName().equals(driverClass)) {
      driver = d;
    }
    if (driver != null) {
      break;
    }
  }

  Objects.requireNonNull(driver, String.format("Did not find registered driver with class %s", driverClass));

  Properties properties = new Properties();
  properties.putAll(options);
  Connection connect;
  String url = options.get(JDBCOptions.JDBC_URL());
  connect = driver.connect(url, properties);
  Objects.requireNonNull(connect, String.format("The driver could not open a JDBC connection. Check the URL: %s", url));
  return connect;
}
 
Example 16
Source File: SimpleDriverDataSource.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Override
protected Connection getConnectionFromDriver(Properties props) throws SQLException {
	Driver driver = getDriver();
	String url = getUrl();
	Assert.notNull(driver, "Driver must not be null");
	if (logger.isDebugEnabled()) {
		logger.debug("Creating new JDBC Driver Connection to [" + url + "]");
	}
	return driver.connect(url, props);
}
 
Example 17
Source File: DriverConnectionProvider.java    From pentaho-reporting with GNU Lesser General Public License v2.1 4 votes vote down vote up
/**
 * Although named getConnection() this method should always return a new connection when being queried or should wrap
 * the connection in a way so that calls to "close()" on that connection do not prevent subsequent calls to this
 * method to fail.
 *
 * @param user
 *          the user name.
 * @param password
 *          the password.
 * @return the connection.
 * @throws SQLException
 *           if the connection has errors.
 */
public Connection createConnection( final String user, final String password ) throws SQLException {
  if ( url == null ) {
    throw new NullPointerException( "URL must not be null when connecting" ); //$NON-NLS-1$
  }

  Driver driverImpl = null;
  try {
    if ( driver != null ) {
      driverImpl = ObjectUtilities.loadAndInstantiate( driver, getClass(), Driver.class );
      if ( driverImpl == null ) {
        logger.warn( "Unable to load specified driver class: " + driver
            + ". See ObjectUtilities logger for error details." );
      }
    }
  } catch ( Throwable e ) {
    throw new SQLException( "Unable to load the driver: " + driver, e.getMessage() ); //$NON-NLS-1$
  }

  final Properties p = new Properties();
  for ( final Map.Entry entry : properties.entrySet() ) {
    final String entryKey = (String) entry.getKey();
    if ( isFilteredKey( entryKey ) ) {
      continue;
    }
    p.setProperty( entryKey, (String) entry.getValue() );
  }
  if ( user != null ) {
    p.setProperty( "user", user );
  }
  if ( password != null ) {
    p.setProperty( "password", password );
  }

  final Connection connection;
  if ( driverImpl != null ) {
    connection = driverImpl.connect( url, p );
  } else {
    connection = DriverManager.getConnection( url, p );
  }
  if ( connection == null ) {
    throw new SQLException( "Driver Manager returned no connection. Your java-implementation is weird." );
  }
  String sqlConnect = p.getProperty( "SQL_CONNECT" );
  if ( !StringUtils.isEmpty( sqlConnect ) ) {
    SqlScriptUtils.execStatements( sqlConnect, connection, false );
  }

  return connection;
}
 
Example 18
Source File: DerbyDatabasesImpl.java    From netbeans with Apache License 2.0 4 votes vote down vote up
/**
 * Creates a new empty database in the Derby system and registers
 * it in the Database Explorer. A <code>DatabaseException</code> is thrown
 * if a database with the given name already exists.
 *
 * <p>This method requires at least the Derby network driver to be registered.
 * Otherwise it will throw an IllegalStateException.</p>
 *
 * <p>This method might take a long time to perform. It is advised that
 * clients do not call this method from the event dispatching thread,
 * where it would block the UI.</p>
 *
 * @param  databaseName the name of the database to created; cannot be nul.
 * @param  user the user to set up authentication for. No authentication
 *         will be set up if <code>user</code> is null or an empty string.
 * @param  password the password for authentication.
 *
 * @throws NullPointerException if <code>databaseName</code> is null.
 * @throws IllegalStateException if the Derby network driver is not registered.
 * @throws DatabaseException if an error occurs while creating the database
 *         or registering it in the Database Explorer.
 * @throws IOException if the Derby system home directory does not exist
 *         and it cannot be created.
 */
public  DatabaseConnection createDatabase(String databaseName, String user, String password) throws DatabaseException, IOException, IllegalStateException {
    if (databaseName == null) {
        throw new NullPointerException("The databaseName parameter cannot be null"); // NOI18N
    }

    ensureSystemHome();
    if (!RegisterDerby.getDefault().ensureStarted(true)) {
        throw new DatabaseException("The Derby server did not start"); // NOI18N
    }

    Driver driver = loadDerbyNetDriver();
    Properties props = new Properties();
    boolean setupAuthentication = (user != null && user.length() >= 0);

    try {
        String url = "jdbc:derby://localhost:" + RegisterDerby.getDefault().getPort() + "/" + databaseName; // NOI18N
        String urlForCreation = url + ";create=true"; // NOI18N
        Connection connection = driver.connect(urlForCreation, props);


        try {
            if (setupAuthentication) {
                setupDatabaseAuthentication(connection, user, password);
            }
        } finally {
            connection.close();
        }

        if (setupAuthentication) {
            // we have to reboot the database for the authentication properties
            // to take effect
            try {
                connection = driver.connect(url + ";shutdown=true", props); // NOI18N
            } catch (SQLException e) {
                // OK, will always occur
            }
        }
    } catch (SQLException sqle) {
        throw new DatabaseException(sqle);
    }

    return registerDatabase(databaseName, user,
            setupAuthentication ? user.toUpperCase() : "APP", // NOI18N
            setupAuthentication ? password : null, setupAuthentication);
}
 
Example 19
Source File: Database.java    From Modern-LWC with MIT License 4 votes vote down vote up
/**
     * Connect to MySQL
     *
     * @return if the connection was successful
     */
    public boolean connect() throws Exception {
        if (connection != null) {
            return true;
        }

        if (currentType == null || currentType == Type.NONE) {
            log("Invalid database engine");
            return false;
        }

        // load the database jar
        ClassLoader classLoader = Bukkit.getServer().getClass().getClassLoader();

        // What class should we try to load?
        String className = "";
        if (currentType == Type.MySQL) {
            className = "com.mysql.jdbc.Driver";
        } else {
            className = "org.sqlite.JDBC";
        }

        // Load the driver class
        Driver driver = (Driver) classLoader.loadClass(className).newInstance();

        // Create the properties to pass to the driver
        Properties properties = new Properties();

        // if we're using MySQL, append the database info
        if (currentType == Type.MySQL) {
            LWC lwc = LWC.getInstance();
            properties.put("autoReconnect", "true");
            properties.put("user", lwc.getConfiguration().getString("database.username"));
            properties.put("password", lwc.getConfiguration().getString("database.password"));
        }

        // Connect to the database
        try {
            connection = driver.connect("jdbc:" + currentType.toString().toLowerCase() + ":" + getDatabasePath(),
                    properties);
            connected = true;
//			setAutoCommit(true);
            return true;
        } catch (SQLException e) {
            log("Failed to connect to " + currentType + ": " + e.getErrorCode() + " - " + e.getMessage());

            if (e.getCause() != null) {
                log("Connection failure cause: " + e.getCause().getMessage());
            }
            return false;
        }
    }
 
Example 20
Source File: RDBInfo.java    From phoebus with Eclipse Public License 1.0 4 votes vote down vote up
/** Create a new {@link Connection} */
public Connection connect() throws Exception
{
    Connection connection = null;

    final Properties prop = new Properties();
    if (user != null)
        prop.put("user", user);
    if (password != null)
        prop.put("password", password);

    if (dialect == Dialect.Oracle)
    {
        // Get class loader to find the driver
        // Class.forName("oracle.jdbc.driver.OracleDriver").getDeclaredConstructor().newInstance();
        // Connect such that Java float and double map to Oracle
        // BINARY_FLOAT resp. BINARY_DOUBLE
        prop.put("SetFloatAndDoubleUseBinary", "true");
    }
    else if (dialect == Dialect.MySQL)
    {
        if (url.startsWith("jdbc:mysql:replication"))
        {
            // Use ReplicationDriver based on code by Laurent Philippe
            // in org.csstudio.platform.utility.rdb.internal.MySQL_RDB
            Driver driver = (Driver)Class.forName("com.mysql.jdbc.ReplicationDriver").getDeclaredConstructor().newInstance();

            // We want this for failover on the slaves
            prop.put("autoReconnect", "true");

            // We want to load balance between the slaves
            prop.put("roundRobinLoadBalance", "true");

            connection = driver.connect(url, prop);
        }
    }
    else if (dialect == Dialect.PostgreSQL)
    {
        // Required to locate driver?
        Class.forName("org.postgresql.Driver").getDeclaredConstructor().newInstance();
    }

    // Unless connection was created by dialect-specific code,
    // use generic driver manager
    if (connection == null)
    {
        try
        {
            connection = DriverManager.getConnection(url, prop);
        }
        catch (Exception ex)
        {
            throw new Exception("Cannot connect to " + url + " as " + user, ex);
        }
    }

    // Basic database info
    if (logger.isLoggable(Level.FINE))
    {
        final DatabaseMetaData meta = connection.getMetaData();
        logger.fine(dialect + " connection: " +
                    meta.getDatabaseProductName() + " " + meta.getDatabaseProductVersion());
    }
    return connection;
}