Example usage for java.sql Driver connect

List of usage examples for java.sql Driver connect

Introduction

In this page you can find the example usage for java.sql Driver connect.

Prototype

Connection connect(String url, java.util.Properties info) throws SQLException;

Source Link

Document

Attempts to make a database connection to the given URL.

Usage

From source file:org.hyperic.hq.plugin.mysql_stats.MySqlStatsMeasurementPlugin.java

protected Connection getConnection(String url, String user, String password) throws SQLException {
    try {//w  w w  .  j  a va2  s .co  m
        password = (password == null) ? "" : password;
        password = (password.matches("^\\s*$")) ? "" : password;
        Driver driver = (Driver) Class.forName(_driver).newInstance();
        final Properties props = new Properties();
        props.put("user", user);
        props.put("password", password);
        return driver.connect(getJdbcUrl(url), props);
    } catch (InstantiationException e) {
        throw new SQLException(e.getMessage());
    } catch (IllegalAccessException e) {
        throw new SQLException(e.getMessage());
    } catch (ClassNotFoundException e) {
        throw new SQLException(e.getMessage());
    }
}

From source file:org.jiemamy.eclipse.core.ui.composer.DbImporterWizardPage.java

/**
 * ??//from   w w  w .j  ava  2s  .  c om
 * 
 * TODO ??????????????????
 */
private void testConnection() {
    final Display display = getShell().getDisplay();
    try {
        final Driver driver = DriverUtil.getDriverInstance(getDriverJarPaths(), getDriverClassName());
        final Properties info = new Properties();
        info.setProperty("user", getUsername());
        info.setProperty("password", getPassword());
        final String uri = getUri();

        new Thread() {

            @Override
            public void run() {
                Connection connection = null;
                try {
                    connection = driver.connect(uri, info);
                    if (connection != null) {
                        display.asyncExec(new Runnable() {

                            public void run() {
                                MessageDialog.openInformation(getShell(), "?",
                                        "???????"); // RESOURCE
                                connectionSucceeded();
                            }
                        });
                    } else {
                        display.asyncExec(new OpenErrorMessageDialog("0", "null connection")); // RESOURCE
                    }
                } catch (SQLException ex) {
                    final String msg = ex.getClass().getName() + " " + ex.getMessage();
                    display.asyncExec(new OpenErrorMessageDialog("1", msg)); // RESOURCE
                } catch (Exception ex) {
                    final String msg = ex.getClass().getName() + " " + ex.getMessage();
                    display.asyncExec(new OpenErrorMessageDialog("2", msg)); // RESOURCE
                } finally {
                    DbUtils.closeQuietly(connection);
                }
            }
        }.start();
    } catch (DriverNotFoundException ex) {
        display.asyncExec(
                new OpenErrorMessageDialog("3", ex.getClass().getName() + " " + ex.getMessage())); // RESOURCE
    } catch (InstantiationException ex) {
        display.asyncExec(
                new OpenErrorMessageDialog("4", ex.getClass().getName() + " " + ex.getMessage())); // RESOURCE
    } catch (IllegalAccessException ex) {
        display.asyncExec(
                new OpenErrorMessageDialog("5", ex.getClass().getName() + " " + ex.getMessage())); // RESOURCE
    } catch (IOException ex) {
        display.asyncExec(
                new OpenErrorMessageDialog("6", ex.getClass().getName() + " " + ex.getMessage())); // RESOURCE
    } catch (Exception ex) {
        display.asyncExec(
                new OpenErrorMessageDialog("7", ex.getClass().getName() + " " + ex.getMessage())); // RESOURCE
    }
}

From source file:org.nuxeo.launcher.config.ConfigurationGenerator.java

/**
 * Check driver availability and database connection
 *
 * @param databaseTemplate Nuxeo database template
 * @param dbName nuxeo.db.name parameter in nuxeo.conf
 * @param dbUser nuxeo.db.user parameter in nuxeo.conf
 * @param dbPassword nuxeo.db.password parameter in nuxeo.conf
 * @param dbHost nuxeo.db.host parameter in nuxeo.conf
 * @param dbPort nuxeo.db.port parameter in nuxeo.conf
 * @throws DatabaseDriverException/*from   ww  w  . j a va 2  s.c o  m*/
 * @throws IOException
 * @throws FileNotFoundException
 * @throws SQLException
 * @since 5.6
 */
public void checkDatabaseConnection(String databaseTemplate, String dbName, String dbUser, String dbPassword,
        String dbHost, String dbPort)
        throws FileNotFoundException, IOException, DatabaseDriverException, SQLException {
    File databaseTemplateDir = new File(nuxeoHome, TEMPLATES + File.separator + databaseTemplate);
    Properties templateProperties = loadTrimmedProperties(new File(databaseTemplateDir, NUXEO_DEFAULT_CONF));
    String classname, connectionUrl;
    if (userConfig.getProperty(PARAM_TEMPLATE_DBNAME).equals(databaseTemplateDir)) {
        // userConfig already includes databaseTemplate
        classname = userConfig.getProperty(PARAM_DB_DRIVER);
        connectionUrl = userConfig.getProperty(PARAM_DB_JDBC_URL);
    } else { // testing a databaseTemplate not included in userConfig
        // check if value is set in nuxeo.conf
        if (userConfig.containsKey(PARAM_DB_DRIVER)) {
            classname = (String) userConfig.get(PARAM_DB_DRIVER);
        } else {
            classname = templateProperties.getProperty(PARAM_DB_DRIVER);
        }
        if (userConfig.containsKey(PARAM_DB_JDBC_URL)) {
            connectionUrl = (String) userConfig.get(PARAM_DB_JDBC_URL);
        } else {
            connectionUrl = templateProperties.getProperty(PARAM_DB_JDBC_URL);
        }
    }
    // Load driver class from template or default lib directory
    Driver driver = lookupDriver(databaseTemplate, databaseTemplateDir, classname);
    // Test db connection
    DriverManager.registerDriver(driver);
    Properties ttProps = new Properties(userConfig);
    ttProps.put(PARAM_DB_HOST, dbHost);
    ttProps.put(PARAM_DB_PORT, dbPort);
    ttProps.put(PARAM_DB_NAME, dbName);
    ttProps.put(PARAM_DB_USER, dbUser);
    ttProps.put(PARAM_DB_PWD, dbPassword);
    TextTemplate tt = new TextTemplate(ttProps);
    String url = tt.processText(connectionUrl);
    Properties conProps = new Properties();
    conProps.put("user", dbUser);
    conProps.put("password", dbPassword);
    log.debug("Testing URL " + url + " with " + conProps);
    Connection con = driver.connect(url, conProps);
    con.close();
}

From source file:org.pentaho.reporting.engine.classic.core.modules.misc.datafactory.sql.DriverConnectionProvider.java

/**
 * 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.//from   w  w w.  j a v  a 2 s. c  o  m
 *
 * @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;
}

From source file:org.pentaho.reporting.engine.classic.core.testsupport.TestSetupModule.java

private void populateDatabase(Driver driver) throws SQLException, IOException {
    Properties p = new Properties();
    p.setProperty("user", "sa");
    p.setProperty("password", "");
    final Connection connection = driver.connect("jdbc:hsqldb:mem:SampleData", p);
    connection.setAutoCommit(false);//  w  w  w . j a v a 2 s  .c  o m
    if (isValid(connection)) {
        // both the test-module here and the sample-data module try to initialize the database.
        // lets do it only once.
        return;
    }
    try {
        final InputStream in = new FileInputStream("target/test-classes/sql/sampledata.script");
        final InputStreamReader inReader = new InputStreamReader(in, "ISO-8859-1");
        final BufferedReader bin = new BufferedReader(inReader, 4096);
        try {
            final Statement statement = connection.createStatement();
            try {
                String line;
                while ((line = bin.readLine()) != null) {
                    if (line.startsWith("CREATE SCHEMA ") || line.startsWith("CREATE USER SA ")
                            || line.startsWith("GRANT DBA TO SA")) {
                        // ignore the error, HSQL sucks
                    } else {
                        statement.addBatch(StringEscapeUtils.unescapeJava(line));
                    }
                }
                statement.executeBatch();
            } finally {
                statement.close();
            }
        } finally {
            bin.close();
        }

        connection.commit();
    } catch (FileNotFoundException fe) {
        DebugLog.log("Unable to populate test database, no script at ./sql/sampledata.script");
    } finally {
        connection.close();
    }
}

From source file:org.pentaho.reporting.engine.classic.extensions.datasources.sampledata.SampleDataModuleInitializer.java

private void populateDatabase(Driver driver) throws SQLException, IOException {
    Properties p = new Properties();
    p.setProperty("user", "sa");
    p.setProperty("password", "");
    final Connection connection = driver.connect("jdbc:hsqldb:mem:SampleData", p);
    connection.setAutoCommit(false);//from  w w  w.j  a  v  a2  s  . c o  m
    try {
        final Configuration config = ClassicEngineBoot.getInstance().getGlobalConfig();
        final String location = config.getConfigProperty(
                "org.pentaho.reporting.engine.classic.extensions.datasources.sampledata.SampleDataLocation");
        final InputStream in = SampleDataModule.class.getResourceAsStream(location);
        if (in == null) {
            logger.warn("Invalid database init-script specified. Sample database will be empty. [" + location
                    + "]");
            return;
        }
        final InputStreamReader inReader = new InputStreamReader(in);
        final BufferedReader bin = new BufferedReader(inReader);
        try {
            final Statement statement = connection.createStatement();
            try {
                String line;
                while ((line = bin.readLine()) != null) {
                    if (line.startsWith("CREATE SCHEMA ") || line.startsWith("CREATE USER SA ")
                            || line.startsWith("GRANT DBA TO SA")) {
                        // ignore the error, HSQL sucks
                    } else {
                        statement.addBatch(StringEscapeUtils.unescapeJava(line));
                    }
                }
                statement.executeBatch();
            } finally {
                statement.close();
            }
        } finally {
            bin.close();
        }

        connection.commit();
    } finally {
        connection.close();
    }
}

From source file:org.seasar.dbflute.helper.jdbc.connection.DfDataSourceHandler.java

protected Connection createConnection() throws SQLException {
    Connection conn = null;//w w  w .  j a v  a 2  s .c  o  m
    final Driver driverInstance = newDriver();
    final Properties info = new Properties();
    if (_connectionProperties != null && !_connectionProperties.isEmpty()) {
        info.putAll(_connectionProperties);
    }
    if (_user == null) {
        String msg = "The database user should not be null.";
        throw new IllegalStateException(msg);
    }
    info.put("user", _user);
    if (_password == null) {
        String msg = "The database password should not be null (but empty allowed).";
        throw new IllegalStateException(msg);
    }
    info.put("password", _password);

    try {
        _log.info("...Connecting to the database:");
        conn = driverInstance.connect(_url, info);
    } catch (SQLException e) {
        String msg = "Failed to connect:";
        msg = msg + " url=" + _url + " user=" + _user;
        throw new DfJDBCException(msg, e);
    }
    if (conn == null) {
        String msg = "The driver didn't understand the URL: " + _url;
        throw new DfJDBCException(msg);
    }
    try {
        conn.setAutoCommit(_autoCommit);
    } catch (SQLException e) {
        String msg = "Failed to set auto commit:";
        msg = msg + " autocommit=" + _autoCommit;
        throw new DfJDBCException(msg, e);
    }
    return conn;
}

From source file:org.talend.metadata.managment.connection.manager.HiveConnectionManager.java

private Connection createHive2StandaloneConnection(IMetadataConnection metadataConn)
        throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {
    Connection conn = null;/*from w ww .  java2 s .  c  om*/
    String connURL = metadataConn.getUrl();
    String username = metadataConn.getUsername();
    String password = metadataConn.getPassword();

    // 1. Get class loader.
    ClassLoader currClassLoader = Thread.currentThread().getContextClassLoader();
    ClassLoader hiveClassLoader = HiveClassLoaderFactory.getInstance().getClassLoader(metadataConn);
    Thread.currentThread().setContextClassLoader(hiveClassLoader);
    try {
        // 2. Fetch the HiveDriver from the new classloader
        Class<?> driver = Class.forName(EDatabase4DriverClassName.HIVE2.getDriverClass(), true,
                hiveClassLoader);
        Driver hiveDriver = (Driver) driver.newInstance();

        // 3. Try to connect by driver
        Properties info = new Properties();
        username = username != null ? username : ""; //$NON-NLS-1$
        password = password != null ? password : "";//$NON-NLS-1$
        info.setProperty("user", username);//$NON-NLS-1$
        info.setProperty("password", password);//$NON-NLS-1$
        conn = hiveDriver.connect(connURL, info);
    } finally {
        Thread.currentThread().setContextClassLoader(currClassLoader);
    }

    return conn;
}

From source file:org.talend.metadata.managment.connection.manager.HiveConnectionManager.java

private Connection createHive1StandaloneConnection(IMetadataConnection metadataConn)
        throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {
    Connection conn = null;/*from   w  w  w .  j  av  a 2 s.c o  m*/
    String connURL = metadataConn.getUrl();
    String username = metadataConn.getUsername();
    String password = metadataConn.getPassword();

    // 1. Get class loader.
    ClassLoader currClassLoader = Thread.currentThread().getContextClassLoader();
    ClassLoader hiveClassLoader = HiveClassLoaderFactory.getInstance().getClassLoader(metadataConn);
    Thread.currentThread().setContextClassLoader(hiveClassLoader);
    try {
        // 2. Fetch the HiveDriver from the new classloader
        Class<?> driver = Class.forName(EDatabase4DriverClassName.HIVE.getDriverClass(), true, hiveClassLoader);
        Driver hiveDriver = (Driver) driver.newInstance();

        // 3. Try to connect by driver
        Properties info = new Properties();
        username = username != null ? username : ""; //$NON-NLS-1$
        password = password != null ? password : "";//$NON-NLS-1$
        info.setProperty("user", username);//$NON-NLS-1$
        info.setProperty("password", password);//$NON-NLS-1$
        conn = hiveDriver.connect(connURL, info);
    } finally {
        Thread.currentThread().setContextClassLoader(currClassLoader);
    }

    return conn;
}

From source file:org.talend.metadata.managment.connection.manager.HiveConnectionManager.java

private Connection createHiveEmbeddedConnection(IMetadataConnection metadataConn)
        throws ClassNotFoundException, InstantiationException, IllegalAccessException {
    String connURL = metadataConn.getUrl();
    String username = metadataConn.getUsername();
    String password = metadataConn.getPassword();

    // 1. Try to connect by driver
    Properties info = new Properties();

    username = username != null ? username : ""; //$NON-NLS-1$
    password = password != null ? password : "";//$NON-NLS-1$
    info.setProperty("user", username);//$NON-NLS-1$
    info.setProperty("password", password);//$NON-NLS-1$
    JavaSqlFactory.doHivePreSetup((DatabaseConnection) metadataConn.getCurrentConnection());

    // 2. Get class loader.
    ClassLoader currClassLoader = Thread.currentThread().getContextClassLoader();
    ClassLoader hiveClassLoader = HiveClassLoaderFactory.getInstance().getClassLoader(metadataConn);
    Thread.currentThread().setContextClassLoader(hiveClassLoader);

    // 3. Fetch the HiveDriver from the new classloader
    Driver hiveDriver = null;
    Connection conn = null;// ww w.  j av a2s  .  c  o  m
    try {
        if (connURL != null) {
            if (connURL.startsWith(DatabaseConnConstants.HIVE_2_URL_FORMAT)) {
                Class<?> driver = Class.forName(EDatabase4DriverClassName.HIVE2.getDriverClass(), true,
                        hiveClassLoader);
                hiveDriver = (Driver) driver.newInstance();
                conn = hiveDriver.connect(connURL, info);
            } else if (connURL.startsWith(DatabaseConnConstants.HIVE_1_URL_FORMAT)) {
                Class<?> driver = Class.forName(EDatabase4DriverClassName.HIVE.getDriverClass(), true,
                        hiveClassLoader);
                hiveDriver = (Driver) driver.newInstance();
                conn = hiveDriver.connect(connURL, info);
            } else {
                // Create a default hive connection.
            }
        }
    } catch (SQLException e) {
        CommonExceptionHandler.process(e);
    } finally {
        Thread.currentThread().setContextClassLoader(currClassLoader);
    }
    setHiveJDBCProperties(metadataConn, conn);
    return conn;
}