gpt4 book ai didi

java - 在Java中的prepered语句中将参数传递给子查询的外表

转载 作者:行者123 更新时间:2023-11-29 19:09:26 25 4
gpt4 key购买 nike

我在 java 中实现了一个子查询,它需要使用准备好的语句提供 2 个参数。

在内部查询中传递参数可以正常工作,但参数不会传递到外部查询。

在执行期间,我在堆栈跟踪上收到错误消息:语句关闭后不允许执行任何操作。因此准备好的语句返回错误的结果。问题:如何才能将参数成功传递到外表。

下面是我的实现的示例代码

pst = conn.prepareStatement("SELECT slot.time_slot_id,slot.`date`,slot.count FROM 
(SELECT time_slot_id,ue.`date`,COUNT(ue.user_id) AS count FROM user_event ue
RIGHT JOIN `time_slot` t ON ue.time_slot_id = t.id
WHERE ue.status= 1 AND event_id=?
GROUP BY ue.`date`,time_slot_id
) AS slot WHERE slot.count >=? ");

pst.setInt(1,eventId);
//here is the parameter that is passed to the outer table
pst.setInt(2,count);
rs = pst.executeQuery();

这是正在实现的整个方法的更新,如下所示;

public static DefaultListModel Fetch(int eventId){
DBconnection.connect();
DefaultListModel fetchedSlots= new DefaultListModel();
try{
//
pst = conn.prepareStatement("SELECT slot.time_slot_id,slot.`date`,slot.count FROM \n" +
"(SELECT time_slot_id,ue.`date`,COUNT(ue.user_id) AS count FROM user_event ue \n" +
"RIGHT JOIN `time_slot` t ON ue.time_slot_id = t.id\n" +
"WHERE ue.status= 1 AND event_id=?\n" +
"GROUP BY ue.`date`,time_slot_id) AS slot\n" +
"WHERE slot.count >? ");
pst.setInt(1,eventId);
//here a function is invocked using eventId to get counts
pst.setInt(2,FetchCounts(eventId));
rs = pst.executeQuery();
while(rs.next()){
fetchedSlots.addElement(new ModelSlot(rs.getInt("time_slot_id"),rs.getString("date")));
}
DBconnection.CloseConnection();
}catch (SQLException ex){
System.out.println(ex.getMessage());
}
return fetchedSlots;
}

最佳答案

我假设错误发生在这样的情况下:

Open statement
...
Use statement
...
Close statement <---------- You can't use your statement after close it
...
Use same statement again <---------- You are here, your statement is close

要解决您的问题,您有两种选择:

编辑

就像我之前说的,当您调用此方法时,您的问题出在连接上:

pst.setInt(2, FetchCounts(eventId));
//---------------^^^

事实上,这会打开一个新连接,然后最终关闭它,因此当您执行查询时rs = pst.executeQuery();,连接被关闭,这会导致这个问题,因此不要关闭方法中的连接 FetchCounts(T eventId);

关于java - 在Java中的prepered语句中将参数传递给子查询的外表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43206754/

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