我尝试从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'是我要更新的其中一列的确切名称......发生了什么?
答案 0 :(得分:1)
您需要在查询中选择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();
}
答案 1 :(得分:0)
您在select sql中错过了userName和pwd。
应该是:
String sql =“SELECT idP,firstName,userName,pwd,lastName,salt FROM PERSON”;