Site Search:

Derby jdbc example improved

Back>

Based on version 1, this program is more concise. When we want to select some columns instead of all columns, we only have to pass an optional field.

package derby;
import java.sql.*;
public class DerbyDb {
    
    /*
     * Download and unzip latest Derby http://db.apache.org/derby/derby_downloads.html
     * Set classpath to point to derby.jar
     * javac -cp "/Users/homenetwork/Downloads/db-derby-10.13.1.1-lib/lib/derby.jar:." DerbyDb.java
     * java -cp "/Users/homenetwork/Downloads/db-derby-10.13.1.1-lib/lib/derby.jar:." DerbyDb
     */
    static final String URL = "jdbc:derby:social;create=true;";
    public static void main(String...args) throws SQLException {
        try(Connection conn = DriverManager.getConnection(URL);
                Statement stmt = conn.createStatement();){
            //stmt.executeUpdate("Drop table people");
            sql(stmt, "create table people ("
                    + "name VARCHAR(255),"
                    + "age INTEGER,"
                    + "emailAddress VARCHAR(255),"
                    + "gender varchar(255))");
            
            sql(stmt, "insert into people values ('Ted', 16, 'ted@email.com', 'MALE')");
            sql(stmt, "insert into people values ('Tedy', 16, 'tedy@email.com', 'MALE')");
            sql(stmt, "select * from people");
            
            System.out.println();
            sql(stmt, "insert into people values ('Min', 36, 'min@email.com', 'MALE')");
            sql(stmt, "select name from people", 1);
            sql(stmt, "Drop table people");
        }
    }
    
    static void sql(Statement stmt, String sql, int... num) throws SQLException {
        int num0 = num.length == 0 ? 4 : num[0];
        boolean isResultSet = stmt.execute(sql);
        if(isResultSet) {
            ResultSet rs = stmt.getResultSet();
            while(rs.next()) {
                for(int i = 1; i <= num0; i++) {
                    System.out.println(" " + rs.getObject(i));
                }
            }
            rs.close(); //closing Statement also closes ResultSet
        } else {
            int r = stmt.getUpdateCount();
            System.out.println(r);
        }
    }


}


Notice you can use rs.getMetaData to gain information about the ColumnCount, ColumnName etc. GetMetaData is not a subject in OCPJP. Besides, create table and delete table is also out of scope for OCPJP.

After this improvement, we are ready to compare sql and java stream api in parallel.