Given the structure of the STUDENT table:

Student (id INTEGER, name VARCHAR)

Given:

public class Test {

    static Connection newConnection = null;

    public static Connection getDBConnection() throws SQLException {
        try (Connection con = DriverManager.getConnection(URL, username, password)) {
            newConnection = con;
        }
        return newConnection;
    }

    public static void main(String[] args) throws SQLException {
        getDBConnection();
        Statement st = newConnection.createStatement();
        st.executeUpdate("INSERT INTO student VALUES (102, 'Kelvin')");
    }
}

Assume that:

The required database driver is configured in the classpath.
The appropriate database is accessible with the URL, userName, and passWord exists.
The SQL query is valid.

What is the result?

A. The program executes successfully and the STUDENT table is updated with one record.
B. The program executes successfully and the STUDENT table is NOT updated with any record.
C. A SQLException is thrown as runtime.
D. A NullPointerException is thrown as runtime.

题解

Connection 对象是 try-with-resources 结构的资源,因此在离开 try-with-resources 结构的 try 区块时会自动调用其 close 方法。由于 Connection 已经 close,所以在第 14 行,尝试使用 Connection 对象来创建 Statement 对象时,会抛出 SQLException。