我正在尝试编写一个程序,以允许用户更新sql数据库中列中的某个值。当我将数据写入数据库时,我正在使用executeQuery
,我去复制并粘贴相同的代码以便在更新值时使用。将executeQuery转换为executeUpdate
我更改了SQL语句来更新值,我读到我需要将我的executeQuery
更改为executeUpdate
。但是,当我去改变,我收到一个错误,说int不能转换为ResultSet
。
case "G":
System.out.println("Enter the player ID:");
String playerId = FileUtility.getInput().nextLine();
System.out.println("Here are the players");
//theList = loadCampersFromDatabase(theList);
for (Player camper : PlayerDAO.selectAllById(playerId)) {
System.out.println(camper);
}
System.out.println("Enter the new amount paid");
int newAmountPaid = FileUtility.getInput().nextInt();
ArrayList<Player> players = new ArrayList();
PreparedStatement ps = null;
String sql = null;
Connection conn = null;
try {
conn = ConnectionUtils.getConnection();
sql = "UPDATE `Camper` SET `amountPaid` where id like ?";
ps = conn.prepareStatement(sql);
ps.setString(1, playerId + "%");
ResultSet rs = ps.executeUpdate();
while (rs.next()) {
int newId = rs.getInt("id");
String firstName = rs.getString("firstName");
String lastName = rs.getString("lastName");
String parentsName = rs.getString("parentsName");
int phoneNumber = rs.getInt("phoneNumber");
String email = rs.getString("email");
int amountPaid = rs.getInt("amountPaid");
players.add(new Player(newId, firstName, lastName,
parentsName, phoneNumber, email, amountPaid));
}
} catch (Exception e) {
String errorMessage = e.getMessage();
e.printStackTrace();
} finally {
DbUtils.close(ps, conn);
}
break;
executeUpdate的返回表示有多少行受到影响,而不是的executeQuery一个int。 – BaSsGaz
@BaSsGaz我不需要在最后返回任何东西,我只需要它来更新表中的那一列 –
您的代码是针对选择查询的结果,您不能将其替换为executeUpdate。您可以在查询之前或之后运行更新,也可以更新结果集而不是运行更新。 – eckes