public void doexample() throws SQLException {
System.out.println("\nRunning tests:");
// First we need a table to store data in
st.executeUpdate("create table basic (a int2, b int2)");
// Now insert some data, using the Statement
st.executeUpdate("insert into basic values (1,1)");
st.executeUpdate("insert into basic values (2,1)");
st.executeUpdate("insert into basic values (3,1)");
// Now change the value of b from 1 to 8
st.executeUpdate("update basic set b=8");
System.out.println("Updated "+st.getUpdateCount()+" rows");
// For large inserts, a PreparedStatement is more efficient, because it
// supports the idea of precompiling the SQL statement, and to store
// directly, a Java object into any column. PostgreSQL doesnt support
// precompiling, but does support setting a column to the value of a
// Java object (like Date, String, etc).
//
// Also, this is the only way of writing dates in a datestyle independent
// manner. (DateStyles are PostgreSQL's way of handling different methods
// of representing dates in the Date data type.)
PreparedStatement ps = db.prepareStatement("insert into basic values (?,?)");
for(int i=2;i< 5;i++) {
ps.setInt(1,4); // "column a" = 5
ps.setInt(2,i); // "column b" = i
ps.executeUpdate(); // executeUpdate because insert returns no data
}
ps.close(); // Always close when we are done with it
// Finally perform a query on the table
System.out.println("performing a query");
ResultSet rs = st.executeQuery("select a, b from basic");
if(rs!=null) {
// Now we run through the result set, printing out the result.
// Note, we must call .next() before attempting to read any results
while(rs.next()) {
int a = rs.getInt("a"); // This shows how to get the value by name
int b = rs.getInt(2); // This shows how to get the value by column
System.out.println(" a="+a+" b="+b);
}
rs.close(); // again, you must close the result when done
}
// Now run the query again, showing a more efficient way of getting the
// result if you don't know what column number a value is in
System.out.println("performing another query");
rs = st.executeQuery("select * from basic where b >1");
if(rs!=null) {
// First find out the column numbers.
//
// It's best to do this here, as calling the methods with the column
// numbers actually performs this call each time they are called. This
// really speeds things up on large queries.
//
int col_a = rs.findColumn("a");
int col_b = rs.findColumn("b");
// Now we run through the result set, printing out the result.
// Again, we must call .next() before attempting to read any results
while(rs.next()) {
int a = rs.getInt(col_a); // This shows how to get the value by name
int b = rs.getInt(col_b); // This shows how to get the value by column
System.out.println(" a="+a+" b="+b);
}
rs.close(); // again, you must close the result when done
}
// The last thing to do is to drop the table. This is done in the
// cleanup() method.
}
This performs the example |