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.apache.drill.jdbc.ITTestShadedJar.java

@Test
public void testDatabaseVersion() throws Exception {

    // print class path for debugging
    System.out.println("java.class.path:");
    System.out.println(System.getProperty("java.class.path"));

    final URLClassLoader loader = (URLClassLoader) ClassLoader.getSystemClassLoader();
    Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
    method.setAccessible(true);/* ww  w.  j  a  v  a  2s .c o m*/
    method.invoke(loader, getJdbcUrl());

    Class<?> clazz = loader.loadClass("org.apache.drill.jdbc.Driver");
    try {
        Driver driver = (Driver) clazz.newInstance();
        try (Connection c = driver.connect("jdbc:drill:drillbit=localhost:31010", null)) {
            DatabaseMetaData metadata = c.getMetaData();
            assertEquals("Apache Drill JDBC Driver", metadata.getDriverName());
            assertEquals("Apache Drill Server", metadata.getDatabaseProductName());
            //assertEquals()
        }
    } catch (Exception ex) {
        throw ex;
    }

}

From source file:org.apache.drill.jdbc.ITTestShadedJar.java

@Test
public void executeJdbcAllQuery() throws Exception {

    // print class path for debugging
    System.out.println("java.class.path:");
    System.out.println(System.getProperty("java.class.path"));

    final URLClassLoader loader = (URLClassLoader) ClassLoader.getSystemClassLoader();
    Method method = URLClassLoader.class.getDeclaredMethod("addURL", URL.class);
    method.setAccessible(true);//from  w  w  w . j  av  a  2  s.  c om
    method.invoke(loader, getJdbcUrl());

    Class<?> clazz = loader.loadClass("org.apache.drill.jdbc.Driver");
    try {
        Driver driver = (Driver) clazz.newInstance();
        try (Connection c = driver.connect("jdbc:drill:drillbit=localhost:31010", null)) {
            String path = Paths.get("").toAbsolutePath().toString() + "/src/test/resources/types.json";
            printQuery(c, "select * from dfs.`" + path + "`");
        }
    } catch (Exception ex) {
        throw ex;
    }

}

From source file:org.apache.falcon.entity.parser.DatasourceEntityParser.java

private static void validateConnection(ClassLoader hdfsClassLoader, String driverClass, String connectUrl,
        Properties userPasswdInfo) throws FalconException {
    try {/*from www  .j  av  a2s  .co  m*/
        java.sql.Driver driver = (java.sql.Driver) hdfsClassLoader.loadClass(driverClass).newInstance();
        LOG.info("Validating connection URL: {0} using driver: {1}", connectUrl, driver.getClass().toString());
        Connection con = driver.connect(connectUrl, userPasswdInfo);
        if (con == null) {
            throw new FalconException("DriverManager.getConnection() return " + "null for URL : " + connectUrl);
        }
    } catch (Exception ex) {
        LOG.error("Exception while validating connection : ", ex);
        throw new FalconException(ex);
    }
}

From source file:org.apache.geronimo.console.databasemanager.wizard.DatabasePoolPortlet.java

private static String attemptConnect(PortletRequest request, PoolData data)
        throws SQLException, IllegalAccessException, InstantiationException {
    Class driverClass = attemptDriverLoad(request, data);
    Driver driver = (Driver) driverClass.newInstance();
    if (driver.acceptsURL(data.url)) {
        Properties props = new Properties();
        if (data.user != null) {
            props.put("user", data.user);
        }//from www  .java 2  s .  co m
        if (data.password != null) {
            props.put("password", data.password);
        }
        Connection con = null;
        try {
            con = driver.connect(data.url, props);
            final DatabaseMetaData metaData = con.getMetaData();
            return metaData.getDatabaseProductName() + " " + metaData.getDatabaseProductVersion();
        } finally {
            if (con != null) {
                try {
                    con.close();
                } catch (SQLException e) {
                    //ignore
                }
            }
        }
    } else
        throw new SQLException("Driver " + data.getDriverClass() + " does not accept URL " + data.url);
}

From source file:org.apache.hadoop.hive.metastore.txn.TxnDbUtil.java

private static Connection getConnection() throws Exception {
    HiveConf conf = new HiveConf();
    String jdbcDriver = HiveConf.getVar(conf, HiveConf.ConfVars.METASTORE_CONNECTION_DRIVER);
    Driver driver = (Driver) Class.forName(jdbcDriver).newInstance();
    Properties prop = new Properties();
    String driverUrl = HiveConf.getVar(conf, HiveConf.ConfVars.METASTORECONNECTURLKEY);
    String user = HiveConf.getVar(conf, HiveConf.ConfVars.METASTORE_CONNECTION_USER_NAME);
    String passwd = ShimLoader.getHadoopShims().getPassword(conf, HiveConf.ConfVars.METASTOREPWD.varname);
    prop.setProperty("user", user);
    prop.setProperty("password", passwd);
    return driver.connect(driverUrl, prop);
}

From source file:org.apache.kylin.jdbc.ITJDBCDriverTest.java

protected Connection getConnection() throws Exception {

    Driver driver = (Driver) Class.forName("org.apache.kylin.jdbc.Driver").newInstance();
    Properties info = new Properties();
    info.put("user", "ADMIN");
    info.put("password", "KYLIN");
    Connection conn = driver.connect("jdbc:kylin://localhost:" + PORT + "/default", info);

    return conn;//from  w w w .  j  av a  2s  .com
}

From source file:org.apache.kylin.jdbc.JDBCDriverTest.java

protected Connection getConnection() throws Exception {

    Driver driver = (Driver) Class.forName("org.apache.kylin.jdbc.Driver").newInstance();
    Properties info = new Properties();
    info.put("user", "ADMIN");
    info.put("password", "KYLIN");
    Connection conn = driver.connect("jdbc:kylin://localhost:7070/default", info);

    return conn;/*w  ww. j  av a  2 s . com*/
}

From source file:org.apache.syncope.installer.validators.PersistenceValidator.java

private Status checkConnection(final DBs selectedDb) {
    Driver driver = null;
    try {/*ww w .j a  va  2s  .  co  m*/
        driver = DriverLoader.load(selectedDb, isProxyEnabled, proxyHost, proxyPort, proxyUser, proxyPwd);
        final Properties props = new Properties();
        props.put("user", persistenceDbuser);
        props.put("password", persistenceDbPassword);
        driver.connect(persistenceUrl, props);
        return Status.OK;
    } catch (Exception ex) {
        error = new StringBuilder("Error during connection to database: please check inserted data.");
        error.append(driver == null ? new StringBuilder(" Unable to get ").append(selectedDb.getName())
                .append(" driver!").toString() : "");
        return Status.ERROR;
    }
}

From source file:org.apache.torque.task.TorqueSQLExec.java

/**
 * Take the base url, the target database and insert a set of SQL
 * files into the target database./*  w w w .  j a v  a2s. c o  m*/
 *
 * @param url
 * @param database
 * @param transactions
 */
private void insertDatabaseSqlFiles(String url, String database, List transactions) {
    url = StringUtils.replace(url, "@DB@", database);
    System.out.println("Our new url -> " + url);

    Driver driverInstance = null;
    try {
        Class dc;
        if (classpath != null) {
            log("Loading " + driver + " using AntClassLoader with classpath " + classpath, Project.MSG_VERBOSE);

            loader = new AntClassLoader(getProject(), classpath);
            dc = loader.loadClass(driver);
        } else {
            log("Loading " + driver + " using system loader.", Project.MSG_VERBOSE);
            dc = Class.forName(driver);
        }
        driverInstance = (Driver) dc.newInstance();
    } catch (ClassNotFoundException e) {
        throw new BuildException("Class Not Found: JDBC driver " + driver + " could not be loaded",
                getLocation());
    } catch (IllegalAccessException e) {
        throw new BuildException("Illegal Access: JDBC driver " + driver + " could not be loaded",
                getLocation());
    } catch (InstantiationException e) {
        throw new BuildException("Instantiation Exception: JDBC driver " + driver + " could not be loaded",
                getLocation());
    }

    try {
        log("connecting to " + url, Project.MSG_VERBOSE);
        Properties info = new Properties();
        info.put("user", userId);
        info.put("password", password);
        conn = driverInstance.connect(url, info);

        if (conn == null) {
            // Driver doesn't understand the URL
            throw new SQLException("No suitable Driver for " + url);
        }

        if (!isValidRdbms(conn)) {
            return;
        }

        conn.setAutoCommit(autocommit);
        statement = conn.createStatement();
        PrintStream out = System.out;
        try {
            if (output != null) {
                log("Opening PrintStream to output file " + output, Project.MSG_VERBOSE);
                out = new PrintStream(new BufferedOutputStream(new FileOutputStream(output)));
            }

            // Process all transactions
            for (Iterator it = transactions.iterator(); it.hasNext();) {
                Transaction transaction = (Transaction) it.next();
                transaction.runTransaction(out);
                if (!autocommit) {
                    log("Commiting transaction", Project.MSG_VERBOSE);
                    conn.commit();
                }
            }
        } finally {
            if (out != null && out != System.out) {
                out.close();
            }
        }
    } catch (IOException e) {
        if (!autocommit && conn != null && onError.equals("abort")) {
            try {
                conn.rollback();
            } catch (SQLException ex) {
                // do nothing.
            }
        }
        throw new BuildException(e, getLocation());
    } catch (SQLException e) {
        if (!autocommit && conn != null && onError.equals("abort")) {
            try {
                conn.rollback();
            } catch (SQLException ex) {
                // do nothing.
            }
        }
        throw new BuildException(e, getLocation());
    } finally {
        try {
            if (statement != null) {
                statement.close();
            }
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
        }
    }

    System.out.println(goodSql + " of " + totalSql + " SQL statements executed successfully");
}

From source file:org.callimachusproject.behaviours.SqlDatasourceSupport.java

private void verifyDriver(String url, Driver driver, Properties props) throws SQLException {
    driver.connect(url, props).close();
}