我正在尝试删除一行,但它不允许我,它说"'deleteRow'不允许,因为ResultSet不是一个可更新的ResultSet"。下面是我的代码:
public void addUserName() throws SQLException {
rs = st.executeQuery("select NAME, prize from usernames");
try {
while (rs.next()) {
String attribute2 = rs.getString("name");
if (attribute2.equals(getName())){
String toPrint = rs.getString(2);
System.out.println("Welcome back " + getName());
System.out.println("You previously won " + toPrint);
System.out.println("Let's see if you can do any better this time :)");
rs.deleteRow();
}
}
} catch (SQLException ex) {
Logger.getLogger(Millionaire.class.getName()).log(Level.SEVERE, null, ex);
}
}
我在这里做错了什么?任何建议将不胜感激。提前谢谢。
这就是我如何创建表,并添加给出的建议,但仍然得到相同的错误:
public void createTable(String tableName) {
try {
Statement stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
//String newTable = "millionair";
//statement.executeUpdate("drop table if exists "+newTable);
String sqlCreateTable = "CREATE TABLE " + tableName + " (NAME VARCHAR(50), PRIZE INT)";
stmt.executeUpdate(sqlCreateTable);
} catch (SQLException ex) {
System.err.println("SQLException: " + ex.getMessage());
}
}
From the docs
一个默认的ResultSet对象是不可更新的,它的游标为只能向前移动。因此,您只能遍历它一次只从第一行到最后一行。生产是可能的可滚动和/或可更新的ResultSet对象。以下代码片段,其中con是一个有效的Connection对象如何使一个结果集是可滚动的和不敏感的更新其他人,这是可以更新的。其他请参见ResultSet字段选项。
Statement stmt = con.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("SELECT a, b FROM TABLE2");
// rs will be scrollable, will not show changes made by others,
// and will be updatable
所以你必须在创建语句时设置ResultSet.CONCUR_UPDATABLE
属性