Skip to content

Instantly share code, notes, and snippets.

@ellios
Created July 23, 2012 04:45
Show Gist options
  • Save ellios/3161996 to your computer and use it in GitHub Desktop.
Save ellios/3161996 to your computer and use it in GitHub Desktop.
DBCPDemo
public class DBCPDemo {
public static void main(String[] args) throws SQLException {
System.out.println("Setting up data source.");
DataSource dataSource = setupDataSource();
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("select * from user");
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) { }
}
printDataSourceStats(dataSource);
shutdownDataSource(dataSource);
}
public static DataSource setupDataSource() {
BasicDataSource ds = new BasicDataSource();
ds.setDriverClassName("org.h2.Driver");
ds.setUsername("sa");
ds.setPassword("");
ds.setUrl("jdbc:h2:file:~/.h2/dbcp;AUTO_SERVER=TRUE");
return ds;
}
public static void printDataSourceStats(DataSource ds) {
BasicDataSource bds = (BasicDataSource) ds;
System.out.println("NumActive: " + bds.getNumActive());
System.out.println("NumIdle: " + bds.getNumIdle());
}
public static void shutdownDataSource(DataSource ds) throws SQLException {
BasicDataSource bds = (BasicDataSource) ds;
bds.close();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment