Appendix 3. Describe the JDBC API

3.1. Identify the Java statements required to connect to a database using JDBC - Source Code

Code:

package c3.s1;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * @author Mikalai Zaikin
 */
public class DerbyTestPreparedStatement {

    public static final String URL = "jdbc:derby://localhost/d:/workspace/ocpjp7-upgrade-samples/sample";

    private void doIt() {
        ResultSet resultSet = null;
        try (Connection connect = DriverManager.getConnection(URL);
             PreparedStatement statement = connect.prepareStatement("SELECT * FROM PERSON");) {

            // Not needed with JDBC 4.0 and later !!!
            // Class.forName("org.apache.derby.jdbc.ClientDriver");

            resultSet = statement.executeQuery();
            while (resultSet.next()) {
                int id = resultSet.getInt("ID");
                String name = resultSet.getString("NAME");
                System.out.print("ID: " + id);
                System.out.println("\t NAME: " + name);
            }
        } catch (Exception e) {
            System.out.println("OUCH !!! \n" + e);
        }
    }

    public static void main(String[] args) throws Exception {
        DerbyTestPreparedStatement test = new DerbyTestPreparedStatement();
        test.doIt();
    }
}
					

output:

ID: 1	 NAME: Mikalai Zaikin
ID: 2	 NAME: Volha Zaikina
ID: 3	 NAME: Anastasia Zaikina
ID: 4	 NAME: Daria Zaikina
ID: 5	 NAME: Ivan Zaikin
					

Code:

package c3.s1;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;

/**
 * @author Mikalai Zaikin
 */
public class DerbyTestStatement {

    public static final String URL = "jdbc:derby://localhost/d:/workspace/ocpjp7-upgrade-samples/sample";

    private void doIt() {
        ResultSet rs = null;
        try (Connection connect = DriverManager.getConnection(URL);
             Statement statement = connect.createStatement();) {

            // Not needed with JDBC 4.0 and later !!!
            // Class.forName("org.apache.derby.jdbc.ClientDriver");

            rs = statement.executeQuery("SELECT * FROM PERSON");
            statement.close();
            while (rs.next()) {
                int id = rs.getInt("ID");
                String name = rs.getString("NAME");
                System.out.print("ID: " + id);
                System.out.println("\tNAME: " + name);
            }
        } catch (Exception e) {
            System.out.println("OUCH !!! \n" + e);
        }
    }

    public static void main(String[] args) throws Exception {
        DerbyTestStatement test = new DerbyTestStatement();
        test.doIt();
    }
}
					

output:

OUCH !!!
java.sql.SQLException: ResultSet not open.  Verify that autocommit is OFF.
					

Professional hosting         Free 'Oracle Certified Expert Web Services Developer 6' Guide     Free SCDJWS 5.0 Guide