我已经看过很多像这样的问题,但是他们都没有我需要的答案。 我创建了一个准备好的语句,它将更新我的表门票。现在,对于方法buyTickets(),我给出了CustomerId(knr),PerformanceId(援助)和Ticekts要购买的参数(anzTickets)。我必须遍历我的查询和每张票(想要的票数 - anzTickets)我必须调用准备好的Statement。但是我收到一条错误,指出ResultSet没有正确定位。我不确定调用next()的位置和方式,以便prepareStatement可以在每一行中执行?这是我的代码:
public void prepareStatements() throws SQLException {
try {
pstmt_updateTicket = connection.prepareStatement("UPDATE Ticket SET kunde = ? WHERE tid = ? AND auffuehrung = ?");
} catch (SQLException ex) {
Logger.getLogger(Szenario1.class.getName()).log(Level.SEVERE, null, ex);
}
}
这是我准备好的陈述,这是我的buyTickets()方法:
public double buyTickets(int knr, int aid, int anzTickets) throws Exception {
double newgesamtpreis = 0;
Statement stmt = connection.createStatement();
PreparedStatement pstmt = pstmt_updateTicket;
try {
int anzT = anzTickets;
int freiTickets = 0;
ResultSet rs = stmt.executeQuery("SELECT tid, count(tid) FROM Ticket WHERE kunde IS NULL GROUP BY tid;");
if (anzT > freiTickets) {
throw new Exception("Es gibt nicht so viele frei Tickets");
} else {
for (int i = 0; i < anzT; i++) {
pstmt.setInt(1, knr);
pstmt.setInt(2, rs.getInt(1));
pstmt.setInt(3, aid);
pstmt.executeUpdate();
rs.next();
}
}
ResultSet rs3 = stmt.executeQuery("SELECT SUM(preis) FROM Ticket WHERE kunde IS NOT NULL");
newgesamtpreis = rs3.getDouble(1);
} catch (Exception ex) {
Logger.getLogger(Szenario1.class.getName()).log(Level.SEVERE, null, ex);
} finally {
stmt.close();
pstmt.close();
}
return newgesamtpreis;
}
答案 0 :(得分:1)
首次创建ResultSet时,它位于之前第一行数据。要迭代ResultSet,您需要先调用 rs.next()
。
rs.next将您带到ResultSet的下一行:
rs.next()
会返回true
rs.next()
返回false
因此,在使用if (rs.next())
或while (rs.next())
时,只有在ResultSet有另一行要检索时才会定位ResultSet。就像它只在一种方法中提供了2种方法rs.hasNext()
和rs.goNext()
。
尝试此:
public double buyTickets(int knr, int aid, int anzTickets) throws Exception {
double newgesamtpreis = 0;
Statement stmt = connection.createStatement();
PreparedStatement pstmt = pstmt_updateTicket;
try {
int anzT = anzTickets;
int freiTickets = 0;
ResultSet rs = stmt.executeQuery("SELECT tid, count(tid) FROM Ticket WHERE kunde IS NULL GROUP BY tid;");
while(rs.next()){
if (anzT > freiTickets) {
throw new Exception("Es gibt nicht so viele frei Tickets");
} else {
for (int i = 0; i < anzT; i++) {
pstmt.setInt(1, knr);
pstmt.setInt(2, rs.getInt(1));
pstmt.setInt(3, aid);
pstmt.executeUpdate();
}
}
ResultSet rs3 = stmt.executeQuery("SELECT SUM(preis) FROM Ticket WHERE kunde IS NOT NULL");
if (rs3.next())
newgesamtpreis = rs3.getDouble(1);
}
} catch (Exception ex) {
Logger.getLogger(Szenario1.class.getName()).log(Level.SEVERE, null, ex);
} finally {
stmt.close();
pstmt.close();
}
return newgesamtpreis;
}
或者每次迭代ResultSet之前只调用rs.next()