List of usage examples for java.sql DriverManager getConnection
@CallerSensitive public static Connection getConnection(String url) throws SQLException
From source file:TXInfo.java
public static void main(String[] a) throws Exception { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con = DriverManager.getConnection("jdbc:odbc:MusicVideo"); int tx = con.getMetaData().getDefaultTransactionIsolation(); String txtxt = null;/*from ww w .java2s . c o m*/ switch (tx) { case Connection.TRANSACTION_NONE: txtxt = "TRANSACTION_NONE"; break; case Connection.TRANSACTION_READ_COMMITTED: txtxt = "TRANSACTION_READ_COMMITTED"; break; case Connection.TRANSACTION_READ_UNCOMMITTED: txtxt = "TRANSACTION_READ_UNCOMMITTED"; break; case Connection.TRANSACTION_REPEATABLE_READ: txtxt = "TRANSACTION_REPEATABLE_READ"; break; case Connection.TRANSACTION_SERIALIZABLE: txtxt = "TRANSACTION_SERIALIZABLE"; break; default: txtxt = "UNKNOWN!!"; } System.out.println(txtxt); con.setTransactionIsolation(tx); System.out.println("Done"); con.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ); System.out.println("TX is now " + con.getTransactionIsolation()); }
From source file:com.kylinolap.query.QueryCli.java
public static void main(String[] args) throws Exception { Options options = new Options(); options.addOption(OPTION_METADATA);/*ww w .jav a 2 s.c om*/ options.addOption(OPTION_SQL); CommandLineParser parser = new GnuParser(); CommandLine commandLine = parser.parse(options, args); KylinConfig config = KylinConfig .createInstanceFromUri(commandLine.getOptionValue(OPTION_METADATA.getOpt())); String sql = commandLine.getOptionValue(OPTION_SQL.getOpt()); Class.forName("net.hydromatic.optiq.jdbc.Driver"); File olapTmp = OLAPSchemaFactory.createTempOLAPJson(null, config); Connection conn = null; Statement stmt = null; ResultSet rs = null; try { conn = DriverManager.getConnection("jdbc:optiq:model=" + olapTmp.getAbsolutePath()); stmt = conn.createStatement(); rs = stmt.executeQuery(sql); int n = 0; ResultSetMetaData meta = rs.getMetaData(); while (rs.next()) { n++; for (int i = 1; i <= meta.getColumnCount(); i++) { System.out.println(n + " - " + meta.getColumnLabel(i) + ":\t" + rs.getObject(i)); } } } finally { if (rs != null) { rs.close(); } if (stmt != null) { stmt.close(); } if (conn != null) { conn.close(); } } }
From source file:JOCLPoolingDriverExample.java
public static void main(String[] args) { //// ww w .j a v a 2 s .com // Just plain-old JDBC. // Connection conn = null; Statement stmt = null; ResultSet rset = null; try { System.out.println("Creating connection."); conn = DriverManager.getConnection(args[0]); System.out.println("Creating statement."); stmt = conn.createStatement(); System.out.println("Executing statement."); rset = stmt.executeQuery(args[1]); System.out.println("Results:"); int numcols = rset.getMetaData().getColumnCount(); while (rset.next()) { for (int i = 1; i <= numcols; i++) { System.out.print("\t" + rset.getString(i)); } System.out.println(""); } } catch (SQLException e) { e.printStackTrace(); } finally { try { if (rset != null) rset.close(); } catch (Exception e) { } try { if (stmt != null) stmt.close(); } catch (Exception e) { } try { if (conn != null) conn.close(); } catch (Exception e) { } } }
From source file:edu.clemson.cs.nestbed.server.tools.BuildTestbed.java
public static void main(String[] args) { try {/*from w w w .j ava 2 s. co m*/ BasicConfigurator.configure(); //loadProperties(); if (args.length < 2) { System.out.println("Usage: BuildTestbed <testbedID> <inputfile>"); System.exit(0); } int testbedID = Integer.parseInt(args[0]); String filename = args[1]; Connection conn = null; Statement statement = null; MoteSqlAdapter adapter = new MoteSqlAdapter(); Map<Integer, Mote> motes = adapter.readMotes(); log.info(motes); String connStr = System.getProperty("nestbed.options.databaseConnectionString"); log.info("connStr: " + connStr); conn = DriverManager.getConnection(connStr); statement = conn.createStatement(); BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(filename))); String line; while ((line = in.readLine()) != null) { StringTokenizer tokenizer = new StringTokenizer(line); int address = Integer.parseInt(tokenizer.nextToken()); String serial = tokenizer.nextToken(); int xLoc = Integer.parseInt(tokenizer.nextToken()); int yLoc = Integer.parseInt(tokenizer.nextToken()); log.info("Input Mote:\n" + "-----------\n" + "address: " + address + "\n" + "serial: " + serial + "\n" + "xLoc: " + xLoc + "\n" + "yLoc: " + yLoc); for (Mote i : motes.values()) { if (i.getMoteSerialID().equals(serial)) { String query = "INSERT INTO MoteTestbedAssignments" + "(testbedID, moteID, moteAddress," + " moteLocationX, moteLocationY) VALUES (" + testbedID + ", " + i.getID() + ", " + address + ", " + xLoc + ", " + yLoc + ")"; log.info(query); statement.executeUpdate(query); } } } conn.commit(); } catch (Exception ex) { log.error("Exception in main", ex); } }
From source file:ProxyAuthTest.java
public static void main(String[] args) throws Exception { if (args.length < 4) { System.out.println("Usage ProxyAuthTest <host> <port> <server_principal> <proxy_user> [testTab]"); System.exit(1);//from w w w . ja v a2s .co m } File currentResultFile = null; String[] beeLineArgs = {}; Class.forName(driverName); String host = args[0]; String port = args[1]; String serverPrincipal = args[2]; String proxyUser = args[3]; String url = null; if (args.length > 4) { tabName = args[4]; } generateData(); generateSQL(null); try { /* * Connect via kerberos and get delegation token */ url = "jdbc:hive2://" + host + ":" + port + "/default;principal=" + serverPrincipal; con = DriverManager.getConnection(url); System.out.println("Connected successfully to " + url); // get delegation token for the given proxy user String token = ((HiveConnection) con).getDelegationToken(proxyUser, serverPrincipal); if ("true".equals(System.getProperty("proxyAuth.debug", "false"))) { System.out.println("Got token: " + token); } con.close(); // so that beeline won't kill the JVM System.setProperty(BEELINE_EXIT, "true"); // connect using principal via Beeline with inputStream url = "jdbc:hive2://" + host + ":" + port + "/default;principal=" + serverPrincipal; currentResultFile = generateSQL(null); beeLineArgs = new String[] { "-u", url, "-n", "foo", "-p", "bar" }; System.out.println("Connection with kerberos, user/password via args, using input rediction"); BeeLine.mainWithInputRedirection(beeLineArgs, inpStream); compareResults(currentResultFile); // connect using principal via Beeline with inputStream url = "jdbc:hive2://" + host + ":" + port + "/default;principal=" + serverPrincipal; currentResultFile = generateSQL(null); beeLineArgs = new String[] { "-u", url, "-n", "foo", "-p", "bar", "-f", scriptFileName }; System.out.println("Connection with kerberos, user/password via args, using input script"); BeeLine.main(beeLineArgs); compareResults(currentResultFile); // connect using principal via Beeline with inputStream url = "jdbc:hive2://" + host + ":" + port + "/default;principal=" + serverPrincipal; currentResultFile = generateSQL(url + " foo bar "); beeLineArgs = new String[] { "-u", url, "-f", scriptFileName }; System.out.println("Connection with kerberos, user/password via connect, using input script"); BeeLine.main(beeLineArgs); compareResults(currentResultFile); // connect using principal via Beeline with inputStream url = "jdbc:hive2://" + host + ":" + port + "/default;principal=" + serverPrincipal; currentResultFile = generateSQL(url + " foo bar "); beeLineArgs = new String[] { "-u", url, "-f", scriptFileName }; System.out.println("Connection with kerberos, user/password via connect, using input redirect"); BeeLine.mainWithInputRedirection(beeLineArgs, inpStream); compareResults(currentResultFile); /* * Connect using the delegation token passed via configuration object */ System.out.println("Store token into ugi and try"); storeTokenInJobConf(token); url = "jdbc:hive2://" + host + ":" + port + "/default;auth=delegationToken"; con = DriverManager.getConnection(url); System.out.println("Connecting to " + url); runTest(); con.close(); // connect using token via Beeline with inputStream url = "jdbc:hive2://" + host + ":" + port + "/default"; currentResultFile = generateSQL(null); beeLineArgs = new String[] { "-u", url, "-n", "foo", "-p", "bar", "-a", "delegationToken" }; System.out.println("Connection with token, user/password via args, using input redirection"); BeeLine.mainWithInputRedirection(beeLineArgs, inpStream); compareResults(currentResultFile); // connect using token via Beeline using script url = "jdbc:hive2://" + host + ":" + port + "/default"; currentResultFile = generateSQL(null); beeLineArgs = new String[] { "-u", url, "-n", "foo", "-p", "bar", "-a", "delegationToken", "-f", scriptFileName }; System.out.println("Connection with token, user/password via args, using input script"); BeeLine.main(beeLineArgs); compareResults(currentResultFile); // connect using token via Beeline using script url = "jdbc:hive2://" + host + ":" + port + "/default"; currentResultFile = generateSQL(url + " foo bar "); beeLineArgs = new String[] { "-a", "delegationToken", "-f", scriptFileName }; System.out.println("Connection with token, user/password via connect, using input script"); BeeLine.main(beeLineArgs); compareResults(currentResultFile); // connect using token via Beeline using script url = "jdbc:hive2://" + host + ":" + port + "/default"; currentResultFile = generateSQL(url + " foo bar "); System.out.println("Connection with token, user/password via connect, using input script"); beeLineArgs = new String[] { "-f", scriptFileName, "-a", "delegationToken" }; BeeLine.main(beeLineArgs); compareResults(currentResultFile); /* * Connect via kerberos with trusted proxy user */ url = "jdbc:hive2://" + host + ":" + port + "/default;principal=" + serverPrincipal + ";hive.server2.proxy.user=" + proxyUser; con = DriverManager.getConnection(url); System.out.println("Connected successfully to " + url); runTest(); ((HiveConnection) con).cancelDelegationToken(token); con.close(); } catch (SQLException e) { System.out.println("*** SQLException: " + e.getMessage() + " : " + e.getSQLState()); e.printStackTrace(); } /* verify the connection fails after canceling the token */ try { url = "jdbc:hive2://" + host + ":" + port + "/default;auth=delegationToken"; con = DriverManager.getConnection(url); throw new Exception("connection should have failed after token cancelation"); } catch (SQLException e) { // Expected to fail due to canceled token } }
From source file:JDBCPool.dbcp.demo.offical.PoolingDriverExample.java
public static void main(String[] args) { // First we load the underlying JDBC driver. // You need this if you don't use the jdbc.drivers system property. System.out.println("Loading underlying JDBC driver."); try {/*from w w w. j av a 2 s . c o m*/ Class.forName("com.cloudera.impala.jdbc4.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } System.out.println("Done."); // Then we set up and register the PoolingDriver. // Normally this would be handled auto-magically by an external configuration, but in this example we'll do it manually. System.out.println("Setting up driver."); try { setupDriver(args[0]); } catch (Exception e) { e.printStackTrace(); } System.out.println("Done."); // // Now, we can use JDBC as we normally would. // Using the connect string // jdbc:apache:commons:dbcp:example // The general form being: // jdbc:apache:commons:dbcp:<name-of-pool> // Connection conn = null; Statement stmt = null; ResultSet rset = null; try { System.out.println("Creating connection."); conn = DriverManager.getConnection("jdbc:apache:commons:dbcp:example"); System.out.println("Creating statement."); stmt = conn.createStatement(); System.out.println("Executing statement."); rset = stmt.executeQuery(args[1]); System.out.println("Results:"); int numcols = rset.getMetaData().getColumnCount(); while (rset.next()) { for (int i = 1; i <= numcols; i++) { System.out.print("\t" + rset.getString(i)); } System.out.println(""); } } catch (SQLException e) { e.printStackTrace(); } finally { try { if (rset != null) rset.close(); } catch (Exception e) { } try { if (stmt != null) stmt.close(); } catch (Exception e) { } try { if (conn != null) conn.close(); } catch (Exception e) { } } // Display some pool statistics try { printDriverStats(); } catch (Exception e) { e.printStackTrace(); } // closes the pool try { shutdownDriver(); } catch (Exception e) { e.printStackTrace(); } }
From source file:PoolingDriverExample.java
public static void main(String[] args) { ///*from www .jav a2s . c o m*/ // First we load the underlying JDBC driver. // You need this if you don't use the jdbc.drivers // system property. // System.out.println("Loading underlying JDBC driver."); try { Class.forName("org.h2.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } System.out.println("Done."); // // Then we set up and register the PoolingDriver. // Normally this would be handled auto-magically by // an external configuration, but in this example we'll // do it manually. // System.out.println("Setting up driver."); try { setupDriver(args[0]); } catch (Exception e) { e.printStackTrace(); } System.out.println("Done."); // // Now, we can use JDBC as we normally would. // Using the connect string // jdbc:apache:commons:dbcp:example // The general form being: // jdbc:apache:commons:dbcp:<name-of-pool> // Connection conn = null; Statement stmt = null; ResultSet rset = null; try { System.out.println("Creating connection."); conn = DriverManager.getConnection("jdbc:apache:commons:dbcp:example"); System.out.println("Creating statement."); stmt = conn.createStatement(); System.out.println("Executing statement."); rset = stmt.executeQuery(args[1]); System.out.println("Results:"); int numcols = rset.getMetaData().getColumnCount(); while (rset.next()) { for (int i = 1; i <= numcols; i++) { System.out.print("\t" + rset.getString(i)); } System.out.println(""); } } catch (SQLException e) { e.printStackTrace(); } finally { try { if (rset != null) rset.close(); } catch (Exception e) { } try { if (stmt != null) stmt.close(); } catch (Exception e) { } try { if (conn != null) conn.close(); } catch (Exception e) { } } // Display some pool statistics try { printDriverStats(); } catch (Exception e) { e.printStackTrace(); } // closes the pool try { shutdownDriver(); } catch (Exception e) { e.printStackTrace(); } }
From source file:ManualPoolingDriverExample.java
public static void main(String[] args) { ////w w w. j ava 2 s. co m // First we load the underlying JDBC driver. // You need this if you don't use the jdbc.drivers // system property. // System.out.println("Loading underlying JDBC driver."); try { Class.forName("oracle.jdbc.driver.OracleDriver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } System.out.println("Done."); // // Then we set up and register the PoolingDriver. // Normally this would be handled auto-magically by // an external configuration, but in this example we'll // do it manually. // System.out.println("Setting up driver."); try { setupDriver(args[0]); } catch (Exception e) { e.printStackTrace(); } System.out.println("Done."); // // Now, we can use JDBC as we normally would. // Using the connect string // jdbc:apache:commons:dbcp:example // The general form being: // jdbc:apache:commons:dbcp:<name-of-pool> // Connection conn = null; Statement stmt = null; ResultSet rset = null; try { System.out.println("Creating connection."); conn = DriverManager.getConnection("jdbc:apache:commons:dbcp:example"); System.out.println("Creating statement."); stmt = conn.createStatement(); System.out.println("Executing statement."); rset = stmt.executeQuery(args[1]); System.out.println("Results:"); int numcols = rset.getMetaData().getColumnCount(); while (rset.next()) { for (int i = 1; i <= numcols; i++) { System.out.print("\t" + rset.getString(i)); } System.out.println(""); } } catch (SQLException e) { e.printStackTrace(); } finally { try { if (rset != null) rset.close(); } catch (Exception e) { } try { if (stmt != null) stmt.close(); } catch (Exception e) { } try { if (conn != null) conn.close(); } catch (Exception e) { } } // Display some pool statistics try { printDriverStats(); } catch (Exception e) { e.printStackTrace(); } // closes the pool try { shutdownDriver(); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.jt.dbcp.example.ManualPoolingDriverExample.java
public static void main(String[] args) { ////from ww w . j a va 2s . c o m // First we load the underlying JDBC driver. // You need this if you don't use the jdbc.drivers // system property. // System.out.println("Loading underlying JDBC driver."); try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { e.printStackTrace(); } System.out.println("Done."); // // Then we set up and register the PoolingDriver. // Normally this would be handled auto-magically by // an external configuration, but in this example we'll // do it manually. // System.out.println("Setting up driver."); try { setupDriver(args[0]); } catch (Exception e) { e.printStackTrace(); } System.out.println("Done."); // // Now, we can use JDBC as we normally would. // Using the connect string // jdbc:apache:commons:dbcp:example // The general form being: // jdbc:apache:commons:dbcp:<name-of-pool> // Connection conn = null; Statement stmt = null; ResultSet rset = null; try { System.out.println("Creating connection."); //pool conn = DriverManager.getConnection("jdbc:apache:commons:dbcp:example"); System.out.println("Creating statement."); stmt = conn.createStatement(); System.out.println("Executing statement."); rset = stmt.executeQuery(args[1]); System.out.println("Results:"); int numcols = rset.getMetaData().getColumnCount(); int count = 0; while (rset.next()) { count++; if (count == 10) { break; } for (int i = 1; i <= numcols; i++) { System.out.print("\t" + rset.getString(i)); } System.out.println(""); } } catch (SQLException e) { e.printStackTrace(); } finally { try { if (rset != null) rset.close(); } catch (Exception e) { } try { if (stmt != null) stmt.close(); } catch (Exception e) { } try { if (conn != null) conn.close(); } catch (Exception e) { } } // Display some pool statistics try { printDriverStats(); } catch (Exception e) { e.printStackTrace(); } // closes the pool try { shutdownDriver(); } catch (Exception e) { e.printStackTrace(); } }
From source file:com.ingby.socbox.bischeck.test.JDBCtest.java
static public void main(String[] args) throws InstantiationException, IllegalAccessException, ClassNotFoundException, SQLException { CommandLineParser parser = new GnuParser(); CommandLine line = null;//from w w w .j a v a 2 s . c o m // create the Options Options options = new Options(); options.addOption("u", "usage", false, "show usage."); options.addOption("c", "connection", true, "the connection url"); options.addOption("s", "sql", true, "the sql statement to run"); options.addOption("m", "meta", true, "get the table meta data"); options.addOption("C", "columns", true, "the number of columns to display, default 1"); options.addOption("d", "driver", true, "the driver class"); options.addOption("v", "verbose", false, "verbose outbout"); try { // parse the command line arguments line = parser.parse(options, args); } catch (org.apache.commons.cli.ParseException e) { System.out.println("Command parse error:" + e.getMessage()); HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("JDBCtest", options); Util.ShellExit(1); } if (line.hasOption("verbose")) { verbose = true; } if (line.hasOption("usage")) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("Bischeck", options); Util.ShellExit(0); } String driverclassname = null; if (!line.hasOption("driver")) { System.out.println("Driver class must be set"); Util.ShellExit(1); } else { driverclassname = line.getOptionValue("driver"); outputln("DriverClass: " + driverclassname); } String connectionname = null; if (!line.hasOption("connection")) { System.out.println("Connection url must be set"); Util.ShellExit(1); } else { connectionname = line.getOptionValue("connection"); outputln("Connection: " + connectionname); } String sql = null; String tablename = null; if (line.hasOption("sql")) { sql = line.getOptionValue("sql"); outputln("SQL: " + sql); } if (line.hasOption("meta")) { tablename = line.getOptionValue("meta"); outputln("Table: " + tablename); } int nrColumns = 1; if (line.hasOption("columns")) { nrColumns = new Integer(line.getOptionValue("columns")); } long execStart = 0l; long execEnd = 0l; long openStart = 0l; long openEnd = 0l; long metaStart = 0l; long metaEnd = 0l; Class.forName(driverclassname).newInstance(); openStart = System.currentTimeMillis(); Connection conn = DriverManager.getConnection(connectionname); openEnd = System.currentTimeMillis(); if (tablename != null) { ResultSet rsCol = null; metaStart = System.currentTimeMillis(); DatabaseMetaData md = conn.getMetaData(); metaEnd = System.currentTimeMillis(); rsCol = md.getColumns(null, null, tablename, null); if (verbose) { tabular("COLUMN_NAME"); tabular("TYPE_NAME"); tabular("COLUMN_SIZE"); tabularlast("DATA_TYPE"); outputln(""); } while (rsCol.next()) { tabular(rsCol.getString("COLUMN_NAME")); tabular(rsCol.getString("TYPE_NAME")); tabular(rsCol.getString("COLUMN_SIZE")); tabularlast(rsCol.getString("DATA_TYPE")); outputln("", true); } } if (sql != null) { Statement stat = conn.createStatement(); stat.setQueryTimeout(10); execStart = System.currentTimeMillis(); ResultSet res = stat.executeQuery(sql); ResultSetMetaData rsmd = res.getMetaData(); execEnd = System.currentTimeMillis(); if (verbose) { for (int i = 1; i < nrColumns + 1; i++) { if (i != nrColumns) tabular(rsmd.getColumnName(i)); else tabularlast(rsmd.getColumnName(i)); } outputln(""); } while (res.next()) { for (int i = 1; i < nrColumns + 1; i++) { if (i != nrColumns) tabular(res.getString(i)); else tabularlast(res.getString(i)); } outputln("", true); } stat.close(); res.close(); } conn.close(); // Print the execution times outputln("Open time: " + (openEnd - openStart) + " ms"); if (line.hasOption("meta")) { outputln("Meta time: " + (metaEnd - metaStart) + " ms"); } if (line.hasOption("sql")) { outputln("Exec time: " + (execEnd - execStart) + " ms"); } }