Example usage for java.sql DriverManager getDriver

List of usage examples for java.sql DriverManager getDriver

Introduction

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

Prototype

@CallerSensitive
public static Driver getDriver(String url) throws SQLException 

Source Link

Document

Attempts to locate a driver that understands the given URL.

Usage

From source file:Test.java

public static void main(String[] args) throws Exception {
    Connection conn = DriverManager.getConnection("...", "username", "password");
    Driver driver = DriverManager.getDriver("jdbc:derby://localhost:1527");
    System.out.println("Parent Logger" + driver.getParentLogger());

}

From source file:Main.java

public static void main(String[] args) throws Exception {

    Class.forName("org.hsqldb.jdbcDriver");
    String url = "jdbc:hsqldb:mem:data/tutorial";

    Driver driver = DriverManager.getDriver(url);

    DriverPropertyInfo[] info = driver.getPropertyInfo(url, null);
    for (int i = 0; i < info.length; i++) {
        System.out.println(info[i].name);
        // Is property value required?
        System.out.println(info[i].required);
        // Get current value
        System.out.println(info[i].value);
        // Get description of property
        System.out.println(info[i].description);

        // Get possible choices for property;
        // if null, value can be any string
        String[] choices = info[i].choices;
        if (choices != null) {
            for (int c = 0; c < choices.length; c++) {
                System.out.println(choices[c]);
            }/*from   w  w w.  j a v  a  2  s  . c om*/
        }
    }

}

From source file:Main.java

public static void main(String[] argv) throws Exception {
    String driverName = "org.gjt.mm.mysql.Driver";
    Class.forName(driverName);//from   ww w  .  j av a 2s  . c om

    String url = "jdbc:mysql://a/b";
    Driver driver = DriverManager.getDriver(url);

    DriverPropertyInfo[] info = driver.getPropertyInfo(url, null);
    for (int i = 0; i < info.length; i++) {
        String name = info[i].name;
        boolean isRequired = info[i].required;
        String value = info[i].value;
        String desc = info[i].description;
        String[] choices = info[i].choices;
    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    Class.forName("org.gjt.mm.mysql.Driver");

    Properties info = new Properties();
    Driver driver = DriverManager.getDriver("jdbc:mysql://localhost/demo2s");
    System.out.println("driver=" + driver);
    DriverPropertyInfo[] attributes = driver.getPropertyInfo("jdbc:mysql://localhost/demo2s", info);
    System.out.println("attributes=" + attributes);
    // zero length means a connection attempt can be made
    System.out.println("Resolving properties for: " + driver.getClass().getName());

    for (int i = 0; i < attributes.length; i++) {
        // get the property metadata
        String name = attributes[i].name;
        String[] choices = attributes[i].choices;
        boolean required = attributes[i].required;
        String description = attributes[i].description;
        // printout property metadata
        System.out.println(name + " (Required: " + required + ")");
        if (choices == null) {
            System.out.println(" No choices.");
        } else {/*from  ww w  .  j  a v a  2  s. c om*/
            System.out.print(" Choices are: ");
            for (int j = 0; j < choices.length; j++) {
                System.out.print(" " + choices[j]);
            }
        }
        System.out.println(" Description: " + description);
    }

}

From source file:TerminalMonitor.java

static public void main(String args[]) {
    DriverPropertyInfo[] required;
    StringBuffer buffer = new StringBuffer();
    Properties props = new Properties();
    boolean connected = false;
    Driver driver;/*from www. j  a  va 2  s.  c om*/
    String url;
    int line = 1; // Mark current input line

    if (args.length < 1) {
        System.out.println("Syntax: <java -Djdbc.drivers=DRIVER_NAME " + "TerminalMonitor JDBC_URL>");
        return;
    }
    url = args[0];
    // We have to get a reference to the driver so we can
    // find out what values to prompt the user for in order
    // to make a connection.
    try {
        driver = DriverManager.getDriver(url);
    } catch (SQLException e) {
        e.printStackTrace();
        System.err.println("Unable to find a driver for the specified " + "URL.");
        System.err.println("Make sure you passed the jdbc.drivers " + "property on the command line to specify "
                + "the driver to be used.");
        return;
    }
    try {
        required = driver.getPropertyInfo(url, props);
    } catch (SQLException e) {
        e.printStackTrace();
        System.err.println("Unable to get driver property information.");
        return;
    }
    input = new BufferedReader(new InputStreamReader(System.in));
    // some drivers do not implement this properly
    // if that is the case, prompt for user name and password
    try {
        if (required.length < 1) {
            props.put("user", prompt("user: "));
            props.put("password", prompt("password: "));
        } else {
            // for each required attribute in the driver property info
            // prompt the user for the value
            for (int i = 0; i < required.length; i++) {
                if (!required[i].required) {
                    continue;
                }
                props.put(required[i].name, prompt(required[i].name + ": "));
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
        System.err.println("Unable to read property info.");
        return;
    }
    // Make the connection.
    try {
        connection = DriverManager.getConnection(url, props);
    } catch (SQLException e) {
        e.printStackTrace();
        System.err.println("Unable to connect to the database.");
    }
    connected = true;
    System.out.println("Connected to " + url);
    // Enter into a user input loop
    while (connected) {
        String tmp, cmd;

        // Print a prompt
        if (line == 1) {
            System.out.print("TM > ");
        } else {
            System.out.print(line + " -> ");
        }
        System.out.flush();
        // Get the next line of input
        try {
            tmp = input.readLine();
        } catch (java.io.IOException e) {
            e.printStackTrace();
            return;
        }
        // Get rid of extra space in the command
        cmd = tmp.trim();
        // The user wants to commit pending transactions
        if (cmd.equals("commit")) {
            try {
                connection.commit();
                System.out.println("Commit successful.");
            } catch (SQLException e) {
                System.out.println("Error in commit: " + e.getMessage());
            }
            buffer = new StringBuffer();
            line = 1;
        }
        // The user wants to execute the current buffer
        else if (cmd.equals("go")) {
            if (!buffer.equals("")) {
                try {
                    executeStatement(buffer);
                } catch (SQLException e) {
                    System.out.println(e.getMessage());
                }
            }
            buffer = new StringBuffer();
            line = 1;
            continue;
        }
        // The user wants to quit
        else if (cmd.equals("quit")) {
            connected = false;
            continue;
        }
        // The user wants to clear the current buffer
        else if (cmd.equals("reset")) {
            buffer = new StringBuffer();
            line = 1;
            continue;
        }
        // The user wants to abort a pending transaction
        else if (cmd.equals("rollback")) {
            try {
                connection.rollback();
                System.out.println("Rollback successful.");
            } catch (SQLException e) {
                System.out.println("An error occurred during rollback: " + e.getMessage());
            }
            buffer = new StringBuffer();
            line = 1;
        }
        // The user wants version info
        else if (cmd.startsWith("show")) {
            DatabaseMetaData meta;

            try {
                meta = connection.getMetaData();
                cmd = cmd.substring(5, cmd.length()).trim();
                if (cmd.equals("version")) {
                    showVersion(meta);
                } else {
                    System.out.println("show version"); // Bad arg
                }
            } catch (SQLException e) {
                System.out.println("Failed to load meta data: " + e.getMessage());
            }
            buffer = new StringBuffer();
            line = 1;
        }
        // The input that is not a keyword should appended be to the buffer
        else {
            buffer.append(" " + tmp);
            line++;
            continue;
        }
    }
    try {
        connection.close();
    } catch (SQLException e) {
        System.out.println("Error closing connection: " + e.getMessage());
    }
    System.out.println("Connection closed.");
}

From source file:com.claresco.tinman.servlet.ConnectionPooling.java

/**
 * Constructor //  www . ja  va 2s . c om
 *
 * Params:
 *
 *
 */
public ConnectionPooling(String connectionURL, String userName, String password, String driverName)
        throws ClassNotFoundException, SQLException {
    Class.forName(driverName);

    Properties props = new Properties();
    props.setProperty("user", userName);
    props.setProperty("password", password);

    ObjectPool connectionPool = new GenericObjectPool(null);

    ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(connectionURL, props);

    PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory,
            connectionPool, null, null, false, true);

    Class.forName("org.apache.commons.dbcp.PoolingDriver");
    PoolingDriver driver = (PoolingDriver) DriverManager.getDriver(myPoolingDriverName);
    driver.registerPool(myPoolName, connectionPool);
}

From source file:com.twosigma.beaker.sql.JDBCClient.java

public BasicDataSource getDataSource(String uri) throws DBConnectionException {
    synchronized (this) {
        try {//w  w  w. ja v  a2  s  .  c  o  m

            BasicDataSource ds = dsMap.get(uri);
            if (ds == null) {
                Driver driver = null;
                for (Driver test : drivers) {
                    if (test.acceptsURL(uri)) {
                        driver = test;
                        break;
                    }
                }
                if (driver == null) {
                    DriverManager.getDriver(uri);
                }
                ds = new BasicDataSource();
                ds.setDriver(driver);
                ds.setUrl(uri);
                dsMap.put(uri, ds);
            }
            return ds;

        } catch (SQLException e) {
            //Logger.getLogger(JDBCClient.class.getName()).log(Level.SEVERE, null, e);
            throw new DBConnectionException(uri, e);
        }
    }
}

From source file:kr.co.bitnine.octopus.frame.ConnectionManager.java

@Override
protected void serviceInit(Configuration conf) throws Exception {
    LOG.info("initialize service - " + getName());

    Class.forName("org.apache.commons.dbcp2.PoolingDriver");
    Class.forName("kr.co.bitnine.octopus.engine.calcite.Driver"); // FIXME:
    poolingDriver = (PoolingDriver) DriverManager.getDriver(DRIVER_PREFIX);

    super.serviceInit(conf);
}

From source file:edu.education.ucsb.muster.MusterServlet.java

private String testConnectivity(DatabaseDefinition db) {

    // load driver
    try {/* w w w  .  j  av a  2s .  com*/
        DriverManager.getDriver(db.url);
    } catch (SQLException e) {
        try {
            DriverManager.registerDriver(
                    (Driver) Class.forName(db.driver).getConstructor().newInstance((Object[]) null));
        } catch (Exception e1) {
            addException(e1, "A driver couldn't be loaded. Check the config file and try again. driver: `"
                    + db.driver + "`, confPath: `" + confPath + "`");
            return "FAIL";
        }
    }

    // connect and test setReadOnly

    // Add the connection to our list and try setting readOnly to test
    Connection connection = null;
    try {
        connection = DriverManager.getConnection(db.url, db.username, db.password);
        connection.setReadOnly(true);
        connection.close();
    } catch (Exception e) {
        addException(e, "Setting readonly failed on " + db.url);
        return e.toString();
    }

    return "OK";
}

From source file:com.zotoh.core.db.JDBCPoolManager.java

private synchronized JDBCPool create(String pool, JDBCInfo param, Properties props) throws SQLException {
    if (existsPool(pool)) {
        throw new SQLException("Jdbc Pool already exists: " + pool);
    }/*from  ww w . j  a  v  a2  s .  co m*/

    PoolableConnectionFactory pcf;
    DriverConnectionFactory dcf;
    GenericObjectPool gop;
    DBVendor dbv;
    ObjectPool p;
    Driver d;

    tlog().debug("JDBCPoolMgr: Driver : {}", param.getDriver());
    tlog().debug("JDBCPoolMgr: URL : {}", param.getUrl());

    //        Ute.loadDriver(param.getDriver());
    d = DriverManager.getDriver(param.getUrl());
    dbv = DBUte.getDBVendor(param);

    dcf = new DriverConnectionFactory(d, param.getUrl(), props);
    gop = new GenericObjectPool();
    gop.setMaxActive(asInt(props.getProperty("max-conns"), 10));
    gop.setTestOnBorrow(true);
    gop.setMaxIdle(gop.getMaxActive());
    gop.setMinIdle(asInt(props.getProperty("min-conns"), 2));
    gop.setMaxWait(asLong(props.getProperty("max-wait4-conn-millis"), 1500L));
    gop.setMinEvictableIdleTimeMillis(asLong(props.getProperty("evict-conn-ifidle-millis"), 300000L));
    gop.setTimeBetweenEvictionRunsMillis(asLong(props.getProperty("check-evict-every-millis"), 60000L));

    pcf = new PoolableConnectionFactory(dcf, gop, null, null, true, false);
    pcf.setDefaultReadOnly(false);
    p = pcf.getPool();

    JDBCPool j = new JDBCPool(dbv, param, p);
    _ps.put(pool, j);

    tlog().debug("JDBCPoolMgr: Added db pool: {}, info= {}", pool, param);
    return j;
}