我试图从mu数据库中的某个表中选择行,并根据结果更新表。经过大量的研究,updateString()和updateRow()似乎是可行的方法。这是我的代码,请注意state
是Statement
类型的全局变量:
public void updateMyRows(Connection conn){
try {
int id;
String firstName, lastName, userName, pwd;
state = conn.createStatement();
String sql = "SELECT idP, firstName, lastName, salt FROM PERSON";
ResultSet rs = state.executeQuery(sql);
while (rs.next()){
id = rs.getInt("idP");
firstName = rs.getString("firstName");
lastName = rs.getString("lastName");
userName = UserNamePwd.userNameGen(lastName, firstName, id);
pwd = UserNamePwd.passWordGen(lastName, firstName, id);
rs.updateString("userName", userName);
rs.updateString("pwd", pwd);
rs.updateRow();
}
rs.close();
state.close();
} catch (Exception e){
e.printStackTrace();
}
}
这样做会导致以下错误:
java.sql.SQLException: Column 'userName' not found.
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:964)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:897)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:886)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:860)
at com.mysql.jdbc.ResultSetImpl.findColumn(ResultSetImpl.java:1077)
at com.mysql.jdbc.ResultSetImpl.updateString(ResultSetImpl.java:7788)
at AddUsersToDB.addUserNamesAndHash(AddUsersToDB.java:79)
at AddUsersToDB.main(AddUsersToDB.java:96)
“用户名”是我要更新的列之一的确切名称。。。发生什么事?
最佳答案
您需要在查询中选择userName
和pwd
列,以便这些列在结果集中可用。我可以在这里使用SELECT *
来获取所有可用的列,不过您可以将userName
和pwd
添加到选择列表中。
String sql = "SELECT * FROM PERSON";
ResultSet rs = state.executeQuery(sql);
while (rs.next()) {
id = rs.getInt("idP");
firstName = rs.getString("firstName");
lastName = rs.getString("lastName");
userName = UserNamePwd.userNameGen(lastName, firstName, id);
pwd = UserNamePwd.passWordGen(lastName, firstName, id);
rs.updateString("userName", userName);
rs.updateString("pwd", pwd);
rs.updateRow();
}