An example of a simple query using JDBC. The following example connects to Dr. Mischief's PostgreSQL database and lists all the evil schemes it can find.
Connection db;
Statement st;
String dbdriverobj = "org.postgresql.Driver";
String dburl =
"jdbc:postgresql:"+
"worlddomination?user=drmischief?password=mUaH4h4H4";
try {
// Load driver
Class.forName(dbdriverobj);
// Connect to the database
db = DriverManager.getConnection(dburl);
// Get political. Er, create object that holds the statement.
st = db.createStatement();
// Execute and get the results...
st.execute("SELECT (date, details) FROM schemes;");
ResultSet results = st.getResultSet();
// Display results.
while(results.next()) {
Object date = results.getObject(1);
Object details = results.getObject(2);
System.out.println(date + ": " + details);
}
} catch (ClassNotFoundException cnfe) {
System.err.println("Class not defined (Is your SQL driver "+
"installed and on classpath?): "+cnfe);
} catch (SQLException se) {
System.err.println("SQL error: "+se);
} catch (Exception e) {
System.err.println("Error: "+e);
}
(Compare to DBI - yeah, these two are very similiar, don't you think?)