List of usage examples for java.sql ResultSet next
boolean next() throws SQLException;
From source file:com.jt.dbcp.example.ManualPoolingDataSourceExample.java
public static void main(String[] args) throws SQLException { ///*from w ww . ja 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 the PoolingDataSource. // 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 data source."); DataSource dataSource = setupDataSource(args[0]); System.out.println("Done."); // // Now, we can use JDBC DataSource as we normally would. // Connection conn = null; Statement stmt = null; ResultSet rset = null; try { System.out.println("Creating connection."); conn = dataSource.getConnection(); 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(""); } printDataSourceStats(dataSource); } 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) { } // shutdownDataSource(dataSource); } }
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 ww . j a v a 2 s.com*/ 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:Main.java
public static void main(String[] args) throws Exception { String driver = "sun.jdbc.odbc.JdbcOdbcDriver"; Connection con;//from w ww .j av a2 s.c o m Statement stmt; ResultSet uprs; try { Class.forName(driver); con = DriverManager.getConnection("jdbc:odbc:RainForestDSN", "student", "student"); stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE); uprs = stmt.executeQuery("SELECT * FROM Records"); // Check the column count ResultSetMetaData md = uprs.getMetaData(); System.out.println("Resultset has " + md.getColumnCount() + " cols."); int rowNum = uprs.getRow(); System.out.println("row1 " + rowNum); uprs.absolute(1); rowNum = uprs.getRow(); System.out.println("row2 " + rowNum); uprs.next(); uprs.moveToInsertRow(); uprs.updateInt(1, 150); uprs.updateString(2, "Madonna"); uprs.updateString(3, "Dummy"); uprs.updateString(4, "Jazz"); uprs.updateString(5, "Image"); uprs.updateInt(6, 5); uprs.updateDouble(7, 5); uprs.updateInt(8, 15); uprs.insertRow(); uprs.close(); stmt.close(); con.close(); } catch (SQLException ex) { System.err.println("SQLException: " + ex.getMessage()); } }
From source file:PoolingDriverExample.java
public static void main(String[] args) { ////from w ww .j a v a2s .com // 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) { ///*from w w w. java 2 s . c om*/ // 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:mx.com.pixup.portal.demo.DemoDisqueraUpdate.java
public static void main(String[] args) { System.out.println("BIENVENIDO A PIXUP"); System.out.println("Mantenimiento catlogo disquera"); System.out.println("Actualizacin de Disquera"); InputStreamReader isr = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(isr); Connection connection = null; Statement statement = null;//from w w w . ja va 2 s . c o m ResultSet resultSet = null; try { BasicDataSource dataSource = new BasicDataSource(); dataSource.setDriverClassName("com.mysql.jdbc.Driver"); dataSource.setUsername("root"); dataSource.setPassword("admin"); dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/pixup"); connection = dataSource.getConnection(); statement = connection.createStatement(); String sql = "select id, nombre from disquera order by nombre"; resultSet = statement.executeQuery(sql); System.out.println("Id Disquera: \t Nombre Disquera"); while (resultSet.next()) { System.out.println(resultSet.getInt("id") + " \t " + resultSet.getString("nombre")); } System.out.println("Proporcione el id de la disquera a actualizar: "); String idDisquera = br.readLine(); System.out.println("Proporcione el nuevo nombre de la disquera: "); String nombreDisquera = br.readLine(); sql = "update disquera set nombre = '" + nombreDisquera + "' where id = " + idDisquera; statement.execute(sql); System.out.println("Disqueras Actualizadas:"); sql = "select id, nombre from disquera order by nombre desc"; resultSet = statement.executeQuery(sql); System.out.println("Id Disquera: \t Nombre Disquera"); while (resultSet.next()) { System.out.println(resultSet.getInt("id") + " \t " + resultSet.getString("nombre")); } } catch (Exception e) { System.out.println("Error en el sistema, intente ms tarde!!"); } finally { if (resultSet != null) { try { resultSet.close(); } catch (Exception e) { } } if (statement != null) { try { statement.close(); } catch (Exception e) { } } if (connection != null) { try { connection.close(); } catch (Exception e) { } } } }
From source file:stockit.ClientFrame.java
/** * @param args the command line arguments *//*from w w w. j ava2 s .com*/ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ username = args[0]; try { DBConnection dbcon = new DBConnection(); dbcon.establishConnection(); Statement stmt = dbcon.con.createStatement(); ResultSet rs = stmt.executeQuery("SELECT C.Name\n" + " FROM Client as C, Account as A\n" + " WHERE C.Client_SSN = A.Client_SSN and\n" + " A.username = \"" + username + "\""); while (rs.next()) { name = rs.getString("Name"); } dbcon.con.close(); //setUpTable(); } catch (Exception ex) { System.out.println(ex.toString()); } try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(ClientFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(ClientFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(ClientFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(ClientFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new ClientFrame().setVisible(true); } }); }
From source file:com.mycompany.mavenproject4.NewMain.java
/** * @param args the command line arguments */// www. j a va 2s . com public static void main(String[] args) { System.out.println("Enter your choice do you want to work with 1.postgre 2.Redis 3.Mongodb"); InputStreamReader IORdatabase = new InputStreamReader(System.in); BufferedReader BIOdatabase = new BufferedReader(IORdatabase); String databasechoice = null; try { databasechoice = BIOdatabase.readLine(); } catch (Exception E7) { System.out.println(E7.getMessage()); } // loading data from the CSV file CsvReader Employees = null; try { Employees = new CsvReader("CSVFile\\Employees.csv"); } catch (FileNotFoundException EB) { System.out.println(EB.getMessage()); } int ColumnCount = 3; int RowCount = 100; int iloop = 0; try { Employees = new CsvReader("CSVFile\\Employees.csv"); } catch (FileNotFoundException E) { System.out.println(E.getMessage()); } String[][] Dataarray = new String[RowCount][ColumnCount]; try { while (Employees.readRecord()) { String v; String[] x; v = Employees.getRawRecord(); x = v.split(","); for (int j = 0; j < ColumnCount; j++) { String value = null; int z = j; value = x[z]; try { Dataarray[iloop][j] = value; } catch (Exception E) { System.out.println(E.getMessage()); } // System.out.println(Dataarray[iloop][j]); } iloop = iloop + 1; } } catch (IOException Em) { System.out.println(Em.getMessage()); } Employees.close(); // connection to Database switch (databasechoice) { // postgre code goes here case "1": Connection Conn = null; Statement Stmt = null; URI dbUri = null; String choice = null; InputStreamReader objin = new InputStreamReader(System.in); BufferedReader objbuf = new BufferedReader(objin); try { Class.forName("org.postgresql.Driver"); } catch (Exception E1) { System.out.println(E1.getMessage()); } String username = "ldoiarosfrzrua"; String password = "HBkE_pJpK5mMIg3p2q1_odmEFX"; String dbUrl = "jdbc:postgresql://ec2-54-83-53-120.compute-1.amazonaws.com:5432/d6693oljh5cco4?ssl=true&sslfactory=org.postgresql.ssl.NonValidatingFactory"; // now update data in the postgress Database // for(int i=0;i<RowCount;i++) // { // try // { // Conn= DriverManager.getConnection(dbUrl, username, password); // Stmt = Conn.createStatement(); // String Connection_String = "insert into EmployeeDistinct (name,jobtitle,department) values (' "+ Dataarray[i][0]+" ',' "+ Dataarray[i][1]+" ',' "+ Dataarray[i][2]+" ')"; // Stmt.executeUpdate(Connection_String); // // } // catch(SQLException E4) // { // System.out.println(E4.getMessage()); // } // } // Quering with the Database System.out.println("1. Display Data "); System.out.println("2. Select data based on primary key"); System.out.println("3. Select data based on Other attributes e.g Name"); System.out.println("Enter your Choice "); try { choice = objbuf.readLine(); } catch (IOException E) { System.out.println(E.getMessage()); } switch (choice) { case "1": try { Conn = DriverManager.getConnection(dbUrl, username, password); Stmt = Conn.createStatement(); String Connection_String = " Select * from EmployeeDistinct;"; ResultSet objRS = Stmt.executeQuery(Connection_String); while (objRS.next()) { System.out.println("Employee ID: " + objRS.getInt("EmployeeID")); System.out.println("Employee Name: " + objRS.getString("Name")); System.out.println("Employee City: " + objRS.getString("Jobtitle")); System.out.println("Employee City: " + objRS.getString("Department")); } } catch (Exception E2) { System.out.println(E2.getMessage()); } break; case "2": System.out.println("Enter the Primary Key"); InputStreamReader objkey = new InputStreamReader(System.in); BufferedReader objbufkey = new BufferedReader(objkey); int key = 0; try { key = Integer.parseInt(objbufkey.readLine()); } catch (IOException E) { System.out.println(E.getMessage()); } try { Conn = DriverManager.getConnection(dbUrl, username, password); Stmt = Conn.createStatement(); String Connection_String = " Select * from EmployeeDistinct where EmployeeID=" + key + ";"; ResultSet objRS = Stmt.executeQuery(Connection_String); while (objRS.next()) { System.out.println("Employee Name: " + objRS.getString("Name")); System.out.println("Employee City: " + objRS.getString("Jobtitle")); System.out.println("Employee City: " + objRS.getString("Department")); } } catch (Exception E2) { System.out.println(E2.getMessage()); } break; case "3": String Name = null; System.out.println("Enter Name to find the record"); InputStreamReader objname = new InputStreamReader(System.in); BufferedReader objbufname = new BufferedReader(objname); try { Name = (objbufname.readLine()).toString(); } catch (IOException E) { System.out.println(E.getMessage()); } try { Conn = DriverManager.getConnection(dbUrl, username, password); Stmt = Conn.createStatement(); String Connection_String = " Select * from EmployeeDistinct where Name=" + "'" + Name + "'" + ";"; ResultSet objRS = Stmt.executeQuery(Connection_String); while (objRS.next()) { System.out.println("Employee ID: " + objRS.getInt("EmployeeID")); System.out.println("Employee City: " + objRS.getString("Jobtitle")); System.out.println("Employee City: " + objRS.getString("Department")); } } catch (Exception E2) { System.out.println(E2.getMessage()); } break; } try { Conn.close(); } catch (SQLException E6) { System.out.println(E6.getMessage()); } break; // Redis code goes here case "2": int Length = 0; String ID = null; Length = 100; // Connection to Redis Jedis jedis = new Jedis("pub-redis-18017.us-east-1-4.6.ec2.redislabs.com", 18017); jedis.auth("7EFOisRwMu8zvhin"); System.out.println("Connected to Redis"); // Storing values in the database // System.out.println("Storing values in the Database might take a minute "); // for(int i=0;i<Length;i++) // { // Store data in redis // int j=i+1; // jedis.hset("Employe:" + j , "Name", Dataarray[i][0]); // jedis.hset("Employe:" + j , "Jobtitle ", Dataarray[i][1]); // jedis.hset("Employe:" + j , "Department", Dataarray[i][2]); // } System.out.println("Search by 1.primary key,2.Name 3.display first 20"); InputStreamReader objkey = new InputStreamReader(System.in); BufferedReader objbufkey = new BufferedReader(objkey); String interimChoice1 = null; try { interimChoice1 = objbufkey.readLine(); } catch (IOException E) { System.out.println(E.getMessage()); } switch (interimChoice1) { case "1": System.out.print("Get details using the primary Key"); InputStreamReader IORKey = new InputStreamReader(System.in); BufferedReader BIORKey = new BufferedReader(IORKey); String ID1 = null; try { ID1 = BIORKey.readLine(); } catch (IOException E3) { System.out.println(E3.getMessage()); } Map<String, String> properties = jedis.hgetAll("Employe:" + Integer.parseInt(ID1)); for (Map.Entry<String, String> entry : properties.entrySet()) { System.out.println("Name:" + jedis.hget("Employee:" + Integer.parseInt(ID1), "Name")); System.out.println("Jobtitle:" + jedis.hget("Employee:" + Integer.parseInt(ID1), "Jobtitle")); System.out .println("Department:" + jedis.hget("Employee:" + Integer.parseInt(ID1), "Department")); } break; case "2": System.out.print("Get details using Department"); InputStreamReader IORName1 = new InputStreamReader(System.in); BufferedReader BIORName1 = new BufferedReader(IORName1); String ID2 = null; try { ID2 = BIORName1.readLine(); } catch (IOException E3) { System.out.println(E3.getMessage()); } for (int i = 0; i < 100; i++) { Map<String, String> properties3 = jedis.hgetAll("Employe:" + i); for (Map.Entry<String, String> entry : properties3.entrySet()) { String value = entry.getValue(); if (entry.getValue().equals(ID2)) { System.out.println("Name:" + jedis.hget("Employee:" + i, "Name")); System.out.println("Jobtitle:" + jedis.hget("Employee:" + i, "Jobtitle")); System.out.println("Department:" + jedis.hget("Employee:" + i, "Department")); } } } //for (Map.Entry<String, String> entry : properties1.entrySet()) //{ //System.out.println(entry.getKey() + "---" + entry.getValue()); // } break; case "3": for (int i = 1; i < 21; i++) { Map<String, String> properties3 = jedis.hgetAll("Employe:" + i); for (Map.Entry<String, String> entry : properties3.entrySet()) { // System.out.println(jedis.hget("Employee:" + i,"Name")); System.out.println("Name:" + jedis.hget("Employee:" + i, "Name")); System.out.println("Jobtitle:" + jedis.hget("Employee:" + i, "Jobtitle")); System.out.println("Department:" + jedis.hget("Employee:" + i, "Department")); } } break; } break; // mongo db code goes here case "3": MongoClient mongo = new MongoClient( new MongoClientURI("mongodb://root2:12345@ds055564.mongolab.com:55564/heroku_766dnj8c")); DB db; db = mongo.getDB("heroku_766dnj8c"); // storing values in the database // for(int i=0;i<100;i++) // { // BasicDBObject document = new BasicDBObject(); // document.put("_id", i+1); // document.put("Name", Dataarray[i][0]); // document.put("Jobtitle", Dataarray[i][1]); // document.put("Department", Dataarray[i][2]); // db.getCollection("EmployeeRaw").insert(document); // } System.out.println("Search by 1.primary key,2.Name 3.display first 20"); InputStreamReader objkey6 = new InputStreamReader(System.in); BufferedReader objbufkey6 = new BufferedReader(objkey6); String interimChoice = null; try { interimChoice = objbufkey6.readLine(); } catch (IOException E) { System.out.println(E.getMessage()); } switch (interimChoice) { case "1": System.out.println("Enter the Primary Key"); InputStreamReader IORPkey = new InputStreamReader(System.in); BufferedReader BIORPkey = new BufferedReader(IORPkey); int Pkey = 0; try { Pkey = Integer.parseInt(BIORPkey.readLine()); } catch (IOException E) { System.out.println(E.getMessage()); } BasicDBObject inQuery = new BasicDBObject(); inQuery.put("_id", Pkey); DBCursor cursor = db.getCollection("EmployeeRaw").find(inQuery); while (cursor.hasNext()) { // System.out.println(cursor.next()); System.out.println(cursor.next()); } break; case "2": System.out.println("Enter the Name to Search"); InputStreamReader objName = new InputStreamReader(System.in); BufferedReader objbufName = new BufferedReader(objName); String Name = null; try { Name = objbufName.readLine(); } catch (IOException E) { System.out.println(E.getMessage()); } BasicDBObject inQuery1 = new BasicDBObject(); inQuery1.put("Name", Name); DBCursor cursor1 = db.getCollection("EmployeeRaw").find(inQuery1); while (cursor1.hasNext()) { // System.out.println(cursor.next()); System.out.println(cursor1.next()); } break; case "3": for (int i = 1; i < 21; i++) { BasicDBObject inQuerya = new BasicDBObject(); inQuerya.put("_id", i); DBCursor cursora = db.getCollection("EmployeeRaw").find(inQuerya); while (cursora.hasNext()) { // System.out.println(cursor.next()); System.out.println(cursora.next()); } } break; } break; } }
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;/* ww w. j a v a 2 s . c om*/ // 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"); } }
From source file:com.jt.dbcp.example.ManualPoolingDriverExample.java
public static void main(String[] args) { ///*from w w w .ja v a 2 s . 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(); } }