Given the records from the Employee table:
eid ename 111 Tom 112 Jerry 113 Donald
and given the code fragment:
try {
Connection conn = DriverManager.getConnection(URL, userName, passWord);
Statement st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
st.execute("SELECT * FROM Employee");
ResultSet rs = st.getResultSet();
while (rs.next()) {
if (rs.getInt(1) == 112) {
rs.updateString(2, "Jack");
}
}
rs.absolute(2);
System.out.println(rs.getInt(1) + " " + rs.getString(2));
} catch (SQLException ex) {
System.out.println("Exception is raised");
}
Assume that:
The appropriate database accessible with the URL, userName, and passWord exists.
What is the result?
A.
The Employee table is updated with the row:
112 Jack
and the program prints:
112 Jerry
B.
The Employee table is updated with the row:
112 Jack
and the program prints:
112 Jack
C.
The Employee table is not updated and the program prints:
112 Jerry
D. The program prints Exception is raised.
题解
第 22 行创建 Statement 对象时所传入的 resultSetType 为 TYPE_SCROLL_INSENSITIVE,因此除了可以用 next 来移动数据列的指针之外,也可以使用 afterLast、previous、absolute 和 relative 等方法。TYPE_SCROLL_SENSITIVE 会使用后来更动的数据;TYPE_SCROLL_INSENSITIVE 会保留数据库中的原始数据,如果想要更动数据库,需要在程序中将列修改之后,明确调用 updateRow 方法。
while 循环会运行三次,走访完所有的结果列。在这个过程中,eid 为 112 的列的第二个字段,「Jerry」字符串会被修改为「Jack」字符串。但由于没有在修改后去调用 updateRow 方法,所以这个修改不会被保留。
