Example usage for java.sql DriverManager registerDriver

List of usage examples for java.sql DriverManager registerDriver

Introduction

In this page you can find the example usage for java.sql DriverManager registerDriver.

Prototype

public static void registerDriver(java.sql.Driver driver) throws SQLException 

Source Link

Document

Registers the given driver with the DriverManager .

Usage

From source file:EditImage.java

private static Connection getConnected(String drivername, String dbstring, String username, String password)
        throws Exception {
    Class drvClass = Class.forName(drivername);
    DriverManager.registerDriver((Driver) drvClass.newInstance());
    return (DriverManager.getConnection(dbstring, username, password));
}

From source file:org.pentaho.platform.dataaccess.datasource.wizard.service.impl.InMemoryConnectionServiceImpl.java

/**
 * NOTE: caller is responsible for closing connection
 *
 * @param ds//  w w w  .j a  v a  2s .  c  o m
 * @return
 * @throws DataSourceManagementException
 */
private static java.sql.Connection getConnection(IDatabaseConnection connection)
        throws ConnectionServiceException {
    java.sql.Connection conn = null;

    String driverClass = connection.getAccessType().getClass().toString();
    if (StringUtils.isEmpty(driverClass)) {
        logger.error(Messages
                .getErrorString("ConnectionServiceInMemoryDelegate.ERROR_0020_CONNECTION_ATTEMPT_FAILED"));
        throw new ConnectionServiceException(Messages
                .getErrorString("ConnectionServiceInMemoryDelegate.ERROR_0020_CONNECTION_ATTEMPT_FAILED")); //$NON-NLS-1$

    }
    Class<?> driverC = null;

    try {
        driverC = Class.forName(driverClass);
    } catch (ClassNotFoundException e) {
        logger.error(Messages.getErrorString(
                "ConnectionServiceInMemoryDelegate.ERROR_0021_DRIVER_NOT_FOUND_IN_CLASSPATH", driverClass), e);
        throw new ConnectionServiceException(Messages.getErrorString(
                "ConnectionServiceInMemoryDelegate.ERROR_0021_DRIVER_NOT_FOUND_IN_CLASSPATH"), e); //$NON-NLS-1$

    }
    if (!Driver.class.isAssignableFrom(driverC)) {
        logger.error(Messages.getErrorString(
                "ConnectionServiceInMemoryDelegate.ERROR_0021_DRIVER_NOT_FOUND_IN_CLASSPATH", driverClass));
        throw new ConnectionServiceException(Messages
                .getErrorString("ConnectionServiceInMemoryDelegate.ERROR_0021_DRIVER_NOT_FOUND_IN_CLASSPATH")); //$NON-NLS-1$

    }
    Driver driver = null;

    try {
        driver = driverC.asSubclass(Driver.class).newInstance();
    } catch (InstantiationException e) {
        logger.error(
                Messages.getErrorString(
                        "ConnectionServiceInMemoryDelegate.ERROR_0022_UNABLE_TO_INSTANCE_DRIVER", driverClass),
                e);
        throw new ConnectionServiceException(Messages
                .getErrorString("ConnectionServiceInMemoryDelegate.ERROR_0022_UNABLE_TO_INSTANCE_DRIVER"), e); //$NON-NLS-1$
    } catch (IllegalAccessException e) {
        logger.error(
                Messages.getErrorString(
                        "ConnectionServiceInMemoryDelegate.ERROR_0022_UNABLE_TO_INSTANCE_DRIVER", driverClass),
                e);
        throw new ConnectionServiceException(Messages
                .getErrorString("ConnectionServiceInMemoryDelegate.ERROR_0022_UNABLE_TO_INSTANCE_DRIVER"), e); //$NON-NLS-1$
    }
    try {
        DriverManager.registerDriver(driver);
        DatabaseDialectService dialectService = new DatabaseDialectService();
        IDatabaseDialect dialect = dialectService.getDialect(connection);

        conn = DriverManager.getConnection(dialect.getURLWithExtraOptions(connection), connection.getUsername(),
                connection.getPassword());
        return conn;
    } catch (SQLException e) {
        logger.error(Messages.getErrorString("ConnectionServiceInMemoryDelegate.ERROR_0023_UNABLE_TO_CONNECT"),
                e);
        throw new ConnectionServiceException(
                Messages.getErrorString("ConnectionServiceInMemoryDelegate.ERROR_0023_UNABLE_TO_CONNECT"), e); //$NON-NLS-1$
    } catch (DatabaseDialectException e) {
        logger.error(Messages.getErrorString("ConnectionServiceInMemoryDelegate.ERROR_0023_UNABLE_TO_CONNECT"),
                e);
        throw new ConnectionServiceException(
                Messages.getErrorString("ConnectionServiceInMemoryDelegate.ERROR_0023_UNABLE_TO_CONNECT"), e); //$NON-NLS-1$
    }
}

From source file:org.LexGrid.LexBIG.Impl.exporters.LexGridToOwlRdfConverter.java

public Store getStore()
        throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {
    if (store_ != null)
        return store_;

    String url = LexEvsServiceLocator.getInstance().getSystemResourceService().getSystemVariables()
            .getAutoLoadDBURL();/*from   w  w  w .  ja v a  2 s .c  o m*/
    String userName = LexEvsServiceLocator.getInstance().getSystemResourceService().getSystemVariables()
            .getAutoLoadDBUsername();
    String password = LexEvsServiceLocator.getInstance().getSystemResourceService().getSystemVariables()
            .getAutoLoadDBPassword();
    org.lexevs.dao.database.type.DatabaseType type = LexEvsServiceLocator.getInstance()
            .getLexEvsDatabaseOperations().getDatabaseType();

    StoreDesc storeDesc = null;

    URLClassLoader loader = LexEvsServiceLocator.getInstance().getSystemResourceService().getClassLoader();

    if (type.equals(org.lexevs.dao.database.type.DatabaseType.MYSQL)) {
        Driver d = (Driver) Class.forName("com.mysql.jdbc.Driver", true, loader).newInstance();
        DriverManager.registerDriver(new DriverShim(d));
        storeDesc = new StoreDesc(LayoutType.LayoutTripleNodesIndex, DatabaseType.MySQL);
    } else if (type.equals(org.lexevs.dao.database.type.DatabaseType.ORACLE)) {
        Driver d = (Driver) Class.forName("oracle.jdbc.driver.OracleDriver", true, loader).newInstance();
        DriverManager.registerDriver(new DriverShim(d));
        storeDesc = new StoreDesc(LayoutType.LayoutTripleNodesIndex, DatabaseType.Oracle);
    } else if (type.equals(org.lexevs.dao.database.type.DatabaseType.POSTGRES)) {
        Driver d = (Driver) Class.forName("org.postgresql.Driver", true, loader).newInstance();
        DriverManager.registerDriver(new DriverShim(d));
        storeDesc = new StoreDesc(LayoutType.LayoutTripleNodesIndex, DatabaseType.PostgreSQL);
    } else if (type.equals(org.lexevs.dao.database.type.DatabaseType.HSQL)) {
        Driver d = (Driver) Class.forName("org.hsqldb.jdbcDriver", true, loader).newInstance();
        DriverManager.registerDriver(new DriverShim(d));
        storeDesc = new StoreDesc(LayoutType.LayoutTripleNodesIndex, DatabaseType.HSQLDB);
    } else if (type.equals(org.lexevs.dao.database.type.DatabaseType.DB2)) {
        Driver d = (Driver) Class.forName("com.ibm.db2.jcc.DB2Driver", true, loader).newInstance();
        DriverManager.registerDriver(new DriverShim(d));
        storeDesc = new StoreDesc(LayoutType.LayoutTripleNodesIndex, DatabaseType.DB2);
    }

    SDBConnection conn = new SDBConnection(url, userName, password);
    store_ = SDBFactory.connectStore(conn, storeDesc);

    // If SDB tables do not exist, it will throw an exception.
    try {
        store_.getSize();
    } catch (Exception e) {
        store_.getTableFormatter().create();
        messenger_.info("create sdb tables.");
        return store_;
    }
    return store_;
}

From source file:net.noctuasource.noctua.core.database.impl.DatabaseInitializerImpl.java

public Connection getConnection() throws SQLException {
    DriverManager.registerDriver(new org.sqlite.JDBC());

    Enumeration<Driver> drivers = DriverManager.getDrivers();
    while (drivers.hasMoreElements()) {
        Driver driver = drivers.nextElement();
        logger.debug("Treiber: " + driver.toString());
    }/*  w ww .  j av a  2 s .com*/

    String connectionString = "jdbc:sqlite:" + databaseFile.toString();
    logger.debug("Connection-String: " + connectionString);
    return DriverManager.getConnection(connectionString);
}

From source file:org.pentaho.metadata.SQLModelGeneratorTest.java

private Connection getDataSourceConnection(String driverClass, String name, String username, String password,
        String url) throws Exception {
    Connection conn = null;/*from   www. j av  a2 s .c o  m*/

    if (StringUtils.isEmpty(driverClass)) {
        throw new Exception("Connection attempt failed"); //$NON-NLS-1$  
    }
    Class<?> driverC = null;

    try {
        driverC = Class.forName(driverClass);
    } catch (ClassNotFoundException e) {
        throw new Exception("Driver not found in the class path. Driver was " + driverClass, e); //$NON-NLS-1$
    }
    if (!Driver.class.isAssignableFrom(driverC)) {
        throw new Exception("Driver not found in the class path. Driver was " + driverClass); //$NON-NLS-1$    }
    }
    Driver driver = null;

    try {
        driver = driverC.asSubclass(Driver.class).newInstance();
    } catch (InstantiationException e) {
        throw new Exception("Unable to instance the driver", e); //$NON-NLS-1$
    } catch (IllegalAccessException e) {
        throw new Exception("Unable to instance the driver", e); //$NON-NLS-1$    }
    }
    try {
        DriverManager.registerDriver(driver);
        conn = DriverManager.getConnection(url, username, password);
        return conn;
    } catch (SQLException e) {
        throw new Exception("Unable to connect", e); //$NON-NLS-1$
    }
}

From source file:org.fastcatsearch.datasource.reader.DBReader.java

private Connection getConnection(JDBCSourceInfo jdbcSourceInfo) throws IRException, SQLException {
    Connection con = null;//ww w.  j  a v  a2  s.c  o m
    logger.debug(">>>>>>>>>>>>>> jdbcSourceInfo > {}", jdbcSourceInfo);
    if (jdbcSourceInfo.getDriver() != null && jdbcSourceInfo.getDriver().length() > 0) {
        Object object = DynamicClassLoader.loadObject(jdbcSourceInfo.getDriver());
        if (object == null) {
            throw new IRException("Cannot find sql driver = " + jdbcSourceInfo.getDriver());
        } else {
            Driver driver = (Driver) object;
            DriverManager.registerDriver(driver);
            Properties info = new Properties();
            info.put("user", jdbcSourceInfo.getUser());
            info.put("password", jdbcSourceInfo.getPassword());
            info.put("connectTimeout", "300000");
            con = driver.connect(jdbcSourceInfo.getUrl(), info);
            con.setAutoCommit(true);
        }
    } else {
        throw new IRException("JDBC driver is empty!");
    }
    return con;
}

From source file:org.apache.slide.store.impl.rdbms.JDBCStore.java

/**
 * Initializes driver.//www .  j  a  va 2 s .c  om
 * <p/>
 * Occurs in four steps :
 * <li>Driver class is loaded</li>
 * <li>Driver is instantiated</li>
 * <li>Driver registration in the driver manager</li>
 * <li>Creation of the basic tables, if they didn't exist before</li>
 * 
 * @exception ServiceInitializationFailedException Throws an exception 
 * if the data source has already been initialized before
 */
public synchronized void initialize(NamespaceAccessToken token) throws ServiceInitializationFailedException {

    // XXX might be done already in setParameter
    if (!alreadyInitialized) {
        try {
            // Loading and registering driver
            getLogger().log("Loading and registering driver '" + driver + "'", LOG_CHANNEL, Logger.INFO);
            Class driverClass = Class.forName(driver);
            Driver driverInstance = (Driver) driverClass.newInstance();

            String levelString = isolationLevelToString(isolationLevel);

            getLogger().log("Setting isolation level '" + levelString + "'", LOG_CHANNEL, Logger.INFO);

            // use DBCP pooling if enabled
            if (useDbcpPooling) {
                getLogger().log("Using DBCP pooling", LOG_CHANNEL, Logger.INFO);
                GenericObjectPool connectionPool = new GenericObjectPool(null);
                if (maxPooledConnections != -1) {
                    connectionPool.setMaxActive(maxPooledConnections);
                }
                getLogger().log("Number of connections set to " + connectionPool.getMaxActive(), LOG_CHANNEL,
                        Logger.INFO);

                DriverManagerConnectionFactory connectionFactory = new DriverManagerConnectionFactory(url, user,
                        password);
                new PoolableConnectionFactory(connectionFactory, connectionPool,
                        // TODO switching on pooling of prepared statements causes problems with closing of connections
                        // switched off for now
                        //                  new StackKeyedObjectPoolFactory(),
                        null, null, false, false, isolationLevel);
                PoolingDriver driver = new PoolingDriver();
                driver.registerPool(dbcpPoolName, connectionPool);
                // already done when loding PoolingDriver class 
                //                DriverManager.registerDriver(driver);
            } else {
                DriverManager.registerDriver(driverInstance);
                getLogger().log("Not using DBCP pooling", LOG_CHANNEL, Logger.WARNING);
            }
        } catch (Exception e) {
            getLogger().log("Loading and registering driver '" + driver + "' failed (" + e.getMessage() + ")",
                    LOG_CHANNEL, Logger.ERROR);
            throw new ServiceInitializationFailedException(this, e);
        } finally {
            alreadyInitialized = true;
        }
    }

}

From source file:org.sqsh.SQLDriverManager.java

/**
 * Check the availability of a specific driver
 * @param name The name of the driver or null if all drivers should be 
 *   checked./* w  w w.  j a  va  2s  .  co m*/
 */
protected void checkDriverAvailability(String name) {

    if (disabledDriverVerification) {

        return;
    }

    for (SQLDriver driver : drivers.values()) {

        if (name == null || driver.getName().equals(name)) {

            ClassLoader driverLoader = driver.getClassLoader(classLoader);

            try {

                Class<? extends Driver> driverClass = Class.forName(driver.getDriverClass(), true, driverLoader)
                        .asSubclass(Driver.class);
                Driver d = driverClass.newInstance();
                DriverManager.registerDriver(new DriverShim(d));

                driver.setAvailable(true);
            } catch (Throwable e) {

                LOG.fine("Unable to load " + driver.getDriverClass() + ": " + e.getMessage());
                driver.setAvailable(false);
            }
        }
    }
}

From source file:org.apache.nifi.dbcp.DBCPConnectionPool.java

/**
 * using Thread.currentThread().getContextClassLoader(); will ensure that you are using the ClassLoader for you NAR.
 *
 * @throws InitializationException//from w  w w . ja v a  2s  . co m
 *             if there is a problem obtaining the ClassLoader
 */
protected ClassLoader getDriverClassLoader(String locationString, String drvName)
        throws InitializationException {
    if (locationString != null && locationString.length() > 0) {
        try {
            // Split and trim the entries
            final ClassLoader classLoader = ClassLoaderUtils.getCustomClassLoader(locationString,
                    this.getClass().getClassLoader(), (dir, name) -> name != null && name.endsWith(".jar"));

            // Workaround which allows to use URLClassLoader for JDBC driver loading.
            // (Because the DriverManager will refuse to use a driver not loaded by the system ClassLoader.)
            final Class<?> clazz = Class.forName(drvName, true, classLoader);
            if (clazz == null) {
                throw new InitializationException("Can't load Database Driver " + drvName);
            }
            final Driver driver = (Driver) clazz.newInstance();
            DriverManager.registerDriver(new DriverShim(driver));

            return classLoader;
        } catch (final MalformedURLException e) {
            throw new InitializationException("Invalid Database Driver Jar Url", e);
        } catch (final Exception e) {
            throw new InitializationException("Can't load Database Driver", e);
        }
    } else {
        // That will ensure that you are using the ClassLoader for you NAR.
        return Thread.currentThread().getContextClassLoader();
    }
}

From source file:com.jaspersoft.jasperserver.api.engine.jasperreports.service.impl.TibcoDriverManagerImpl.java

static void registerDriver(String driverClassName) {
    if (isDriverExisted(driverClassName))
        return;/*from ww w .  ja v a2  s  . c om*/
    Class<?> tibcoDriver = null;
    Constructor<?> tdConstructor = null;
    Driver driver = null;
    if (driverClassName != null) {
        try {
            tibcoDriver = Class.forName(driverClassName);
            tdConstructor = tibcoDriver.getDeclaredConstructor();
            driver = (Driver) tdConstructor.newInstance((Object[]) null);
            DriverManager.registerDriver(driver);
        } catch (Exception ex) {
        }
        if (tibcoDriver == null)
            printLog("Couldn't Class.forName for " + driverClassName);
        else if (tdConstructor == null)
            printLog("Couldn't get constructor for " + driverClassName);
        else if (driver == null)
            printLog("Couldn't instantiate " + driverClassName);
    }
}