gpt4 book ai didi

java - 执行 SELECT 查询时,PreparedStatement 和 ResultSet 出现问题?

转载 作者:行者123 更新时间:2023-12-02 04:56:41 25 4
gpt4 key购买 nike

UPDATE和INSERT查询没有问题,只有SELECT有问题,这里是所有代码:

try {
String nCard = jTextField1.getText();
String deprecate = jTextField2.getText();
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
String url = "jdbc:mysql://localhost:3306/visits";
Connection conn1 = DriverManager.getConnection(url, "root", "");

PreparedStatement pstmt = conn1.prepareStatement("INSERT INTO `visits`.`transaction` (`numbercard`, `deprecate`) VALUES (?, ?)");
pstmt.setString(1, nCard);
pstmt.setString(2, deprecate);
pstmt.executeUpdate();

DrawTable();

PreparedStatement pstmt1 = conn1.prepareStatement("SELECT `balance` FROM `visitor` WHERE `cardID`=?");
int nCardInt = Integer.parseInt(nCard);
pstmt1.setInt(1, nCardInt);
ResultSet rs1 = pstmt1.executeQuery();
int tempBonus=rs1.getInt(1);
tempBonus-=Integer.parseInt(deprecate);
String bonusString = String.valueOf(tempBonus);

PreparedStatement pstmt2 = conn1.prepareStatement("UPDATE `visitor` SET `balance`=? WHERE cardID=?");
pstmt2.setString(1, bonusString);
pstmt2.setString(2, nCard);
pstmt2.executeUpdate();
} catch (SQLException ex) {
Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}

我只需要 1 个 ID 单元格即可对其进行操作,“SELECT balance FROM visitor WHERE cardID =?”。如果有人提出更简单的方法,我将非常感激。

最佳答案

您忘记调用 next() ,这会将光标前进到第一行(如果存在)。

A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the first row the current row; the second call makes the second row the current row, and so on.

if (rs1.next())
{
int tempBonus=rs1.getInt(1);
}

关于java - 执行 SELECT 查询时,PreparedStatement 和 ResultSet 出现问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28703816/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com