我正在尝试编写一个程序,允许用户更新sql数据库中列中的某个值。当我将数据写入数据库时,我正在使用executeQuery
,我在复制和粘贴相同的代码时使用了更新值。
我更改了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;
答案 0 :(得分:0)
您对executeUpdate()和executeQuery()方法感到困惑。
我建议你重做你方法的逻辑。 我可以看到您的更新查询,您只传递了一个值为&#39; id&#39;在查询中,而不是在&#39; amountPaid&#39; 重写update语句并使用executeUpdate()方法进行更新。
答案 1 :(得分:0)
只需将Resultset
及其相应的while
循环移除为操作查询(UPDATE
,INSERT
,DELETE
,CREATE
,{{ 1}},ALTER
)不返回结果集,仅返回DROP
个查询。下面假设您打算将 newAmountPaid 绑定到查询中:
SELECT