Allright been trying to figure this out the last 2 days.
Statement statement = con.createStatement();
String query = "SELECT * FROM sell";
ResultSet rs = query(query);
while (rs.next()){//<--- I get there operation error here
This is the query method.
public static ResultSet query(String s) throws SQLException {
try {
if (s.toLowerCase().startsWith("select")) {
if(stm == null) {
createConnection();
}
ResultSet rs = stm.executeQuery(s);
return rs;
} else {
if(stm == null) {
createConnection();
}
stm.executeUpdate(s);
}
return null;
} catch (Exception e) {
e.printStackTrace();
con = null;
stm = null;
}
return null;
}
How can I fix this error?
wattostudios
8,62613 gold badges42 silver badges57 bronze badges
asked Jun 7, 2012 at 14:01
2
It’s hard to be sure just from the code you’ve posted, but I suspect that the ResultSet is inadvertently getting closed (or stm is getting reused) inside the body of the while loop. This would trigger the exception at the start of the following iteration.
Additionally, you need to make sure there are no other threads in your application that could potentially be using the same DB connection or stm object.
answered Jun 7, 2012 at 14:06
NPENPE
478k105 gold badges939 silver badges1006 bronze badges
1
IMHO, you should do everything you need with your ResultSet before you close your connection.
answered Jun 7, 2012 at 14:22
iozeeiozee
1,3391 gold badge12 silver badges24 bronze badges
there are few things you need to fix. Opening a connection, running a query to get the rs, closing it, and closing the connection all should be done in the same function scope as far as possible. from your code, you seem to use the «con» variable as a global variable, which could potentially cause a problem. you are not closing the stm object. or the rs object. this code does not run for too long, even if it has no errors. Your code should be like this:
if (stringUtils.isBlank(sql)){
throw new IllegalArgumentsException ("SQL statement is required");
}
Connection con = null;
PreparedStatement ps =null;
Resultset rs = null;
try{
con = getConnection();
ps = con.preparestatement(sql);
rs = ps.executeQuery();
processResults(rs);
close(rs);
close(ps);
close(con);
}catch (Execption e){
log.Exception ("Error in: {}", sql, e);
throw new RuntimeException (e);
}finally{
close(rs);
close(ps);
close(con);
}
answered Jun 7, 2012 at 14:33
srini.venigallasrini.venigalla
5,0891 gold badge18 silver badges29 bronze badges
use another Statement object in inner loop
Like
Statement st,st1;
st=con.createStatement();
st1=con.createStatement();
//in Inner loop
while(<<your code>>)
{
st1.executeQuery(<<your query>>);
}
![]()
answered Jun 30, 2013 at 1:33
![]()
I know this is a few years late, but I’ve found that synchronizing the db methods usually get rid of this problem.
answered Nov 22, 2013 at 8:39
ZeeZee
1,55212 silver badges24 bronze badges
0
- Java Error
java.sql.SQLException: Operation not allowed after ResultSet closed - Fix Java Error
java.sql.SQLException: Operation not allowed after ResultSet closed

This tutorial demonstrates the java.sql.SQLException: Operation not allowed after ResultSet closed error in Java.
Java Error java.sql.SQLException: Operation not allowed after ResultSet closed
The error Operation Not Allowed After Resultset Closed is an SQL exception when we try to access a closed result set. As the Java Doc mentions, whenever a statement object is closed, If its Resultset object exists, it will also be closed.
The problem with the error is that the Resultset instance will also save the underlying statement. So when the underlying statement is closed, the Resultset will also be closed, which throws the error.
Here’s a snippet of code that will throw the same error.
Code:
ResultSet Result_Set; // class variable
Statement Demo_Statement = null;
try{
Demo_Statement = DB_Connection.createStatement();
Result_Set = Demo_Statement.getGeneratedKeys();
}
catch (Exception e){
throw e;
}
finally{
try{
if (Demo_Statement != null)
Demo_Statement.close();
} catch (SQLException e){
throw e;
}
}
System.out.println(Result_Set.next());
The code above with a database connection will throw the following error.
java.sql.SQLException: Operation not allowed after ResultSet closed
Fix Java Error java.sql.SQLException: Operation not allowed after ResultSet closed
The problem in the code is that we cannot close the statement instance before we are done with Resultset. Once we are done with the Resultset, we can close both Resultset and Statement Instance.
As we can see, we are trying to print the Boolean from Result_Set.next(), but we are using the Resultset after closing the statement instance, which is also closing the Resultset.
In the code above, the fix will be not to close the statement at this place or not to use the Resultset after closing the statement instance. It is based on your application either we can remove the Demo_Statement.close() or the System.out.println(Result_Set.next()); statement.
Code:
ResultSet Result_Set; // class variable
Statement Demo_Statement = null;
try{
Demo_Statement = DB_Connection.createStatement();
Result_Set = Demo_Statement.getGeneratedKeys();
}
catch (Exception e){
throw e;
}
finally{
try{
if (Demo_Statement != null)
Demo_Statement.close();
} catch (SQLException e){
throw e;
}
}
We just removed the part where we are trying the use the Resultset after the statement instance is closed. Once all the operations are done with the Resultset, we can close both the statement instance and Resultset.
|
igoRRR 1 / 1 / 0 Регистрация: 12.01.2010 Сообщений: 13 |
||||
|
1 |
||||
|
MySQL 04.04.2015, 00:20. Показов 6062. Ответов 2 Метки нет (Все метки)
Не давно начал изучать эту тему и столкнулся с проблемой. В общем у меня строится JTree на основе БД, получилось связать две таблицы, но при добавлении третей то есть третьего вложения выскакивает ошибка «Operation not allowed after ResultSet closed». Вот код
Может кто-нибудь поможет? Заранее благодарен.
__________________
0 |
|
Programming Эксперт 94731 / 64177 / 26122 Регистрация: 12.04.2006 Сообщений: 116,782 |
04.04.2015, 00:20 |
|
Ответы с готовыми решениями: Вернуть ResultSet JDBC: ResultSet ResultSet не определяется Сразу к делу. Взял коннектор с оф. сайта… ResultSet and Proccess 2 |
|
185 / 160 / 49 Регистрация: 30.07.2013 Сообщений: 508 |
|
|
05.04.2015, 01:23 |
2 |
|
Ты один Statement (stm) используешь для нескольких ResultSet. Как только ты получил данные для rs4 , то rs3 у тебя закрывается.
1 |
|
1 / 1 / 0 Регистрация: 12.01.2010 Сообщений: 13 |
|
|
05.04.2015, 14:25 [ТС] |
3 |
|
darknim, всё отлично заработало!
0 |
- Thread Status:
-
Not open for further replies.
-
Whenever I try to run redeemAll() it throws an error
WebItem
- package me.mrkirby153.plugins.cloudshop.web;
- import me.mrkirby153.plugins.cloudshop.CloudShop;
- import me.mrkirby153.plugins.cloudshop.utils.ChatHelper;
- import org.bukkit.ChatColor;
- import org.bukkit.entity.Player;
- import java.sql.ResultSet;
- import java.sql.SQLException;
- private static CloudShop plugin = CloudShop.instance();
- private static MySQL sql = plugin.mySQL;
- public static void redeemAll(Player player) {
- int slotsRequired = ItemConstructor.getInventorySlotsRequired(player);
- for (int i = 0; i < player.getInventory().getSize(); i++) {
- if (player.getInventory().getContents()[i] == null)
- if (openSlots < slotsRequired) {
- ChatHelper.sendToPlayer(player, ChatColor.RED + "You do not have enough open slots in your inventory to receive your items. " +
- "You have " + ChatColor.GOLD + openSlots + ChatColor.RED + " avalable and you need " + ChatColor.GOLD + slotsRequired);
- ResultSet rs = sql.executeQuery("SELECT * FROM `cs_bought` WHERE `boughtBy` = '" + player.getName() + "'");
- int productId = rs.getInt("productId");
- ItemConstructor.redeemItem(player, productId);
- ChatHelper.sendToPlayer(player, ChatColor.GREEN + "Redeemed " + count + " items!");
- ChatHelper.sendToPlayer(player, ChatColor.LIGHT_PURPLE + "There was a problem redeeming your items. " +
- "Please contact an administrator for help. " + ChatColor.GOLD + e.getMessage());
Error:[14:07:33] [Server thread/WARN]: java.sql.SQLException: Operation not allowed after ResultSet closed [14:07:33] [Server thread/WARN]: at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1073) [14:07:33] [Server thread/WARN]: at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:987) [14:07:33] [Server thread/WARN]: at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:982) [14:07:33] [Server thread/WARN]: at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:927) [14:07:33] [Server thread/WARN]: at com.mysql.jdbc.ResultSetImpl.checkClosed(ResultSetImpl.java:794) [14:07:33] [Server thread/WARN]: at com.mysql.jdbc.ResultSetImpl.next(ResultSetImpl.java:7145) [14:07:33] [Server thread/WARN]: at me.mrkirby153.plugins.cloudshop.web.WebItem.redeemAll(WebItem.java:31) [14:07:33] [Server thread/WARN]: at me.mrkirby153.plugins.cloudshop.command.CloudShopCommand.onCommand(CloudShopCommand.java:48) [14:07:33] [Server thread/WARN]: at org.bukkit.command.PluginCommand.execute(PluginCommand.java:44) [14:07:33] [Server thread/WARN]: at org.bukkit.command.SimpleCommandMap.dispatch(SimpleCommandMap.java:196) [14:07:33] [Server thread/WARN]: at org.bukkit.craftbukkit.v1_7_R1.CraftServer.dispatchCommand(CraftServer.java:542) [14:07:33] [Server thread/WARN]: at net.minecraft.server.v1_7_R1.PlayerConnection.handleCommand(PlayerConnection.java:932) [14:07:33] [Server thread/WARN]: at net.minecraft.server.v1_7_R1.PlayerConnection.a(PlayerConnection.java:814) [14:07:33] [Server thread/WARN]: at net.minecraft.server.v1_7_R1.PacketPlayInChat.a(PacketPlayInChat.java:28) [14:07:33] [Server thread/WARN]: at net.minecraft.server.v1_7_R1.PacketPlayInChat.handle(PacketPlayInChat.java:47) [14:07:33] [Server thread/WARN]: at net.minecraft.server.v1_7_R1.NetworkManager.a(NetworkManager.java:146) [14:07:33] [Server thread/WARN]: at net.minecraft.server.v1_7_R1.ServerConnection.c(SourceFile:134) [14:07:33] [Server thread/WARN]: at net.minecraft.server.v1_7_R1.MinecraftServer.u(MinecraftServer.java:655) [14:07:33] [Server thread/WARN]: at net.minecraft.server.v1_7_R1.DedicatedServer.u(DedicatedServer.java:250) [14:07:33] [Server thread/WARN]: at net.minecraft.server.v1_7_R1.MinecraftServer.t(MinecraftServer.java:545) [14:07:33] [Server thread/WARN]: at net.minecraft.server.v1_7_R1.MinecraftServer.run(MinecraftServer.java:457) [14:07:33] [Server thread/WARN]: at net.minecraft.server.v1_7_R1.ThreadServerApplication.run(SourceFile:617)
-
Could you please post your «executeQuery» method in your MySQL class? You are probably closing the ResultSet there before your return it. rs.next() will not work after the ResultSet was closed.
-
blablubbabc
- rs = st.executeQuery(query);
- ChatHelper.debug("Executed Query " + query + "!");
- ChatHelper.debug("An error occured when trying to execute '" + query + "': " + e.getMessage());
-
Hmm, I assume «st» is a Statement which you seem to share across all your queries? Are you somewhere doing another query/using that same Statement object or closing the Statement at the same time (maybe asynchronous)?
The ResultSet could also be closed if the Statement is used again (for another query) or closed itself..But besides of that I currently don’t see where the ResultSet might be getting closed..

-
blablubbabc
I don’t know why either. All my other queries work just fine!blablubbabc
Also found something interesting, If I have more than one valuemy debug statements tell me that it only runs for the first productId in the table!
EDIT by Moderator: merged posts, please use the edit button instead of double posting.
Last edited by a moderator: Jun 6, 2016
-
mrkirby153
ItemConstructor.redeemItem(player, productId);
Is this method by chance doing a query itself? If this is the case then we have found the issue..
The old ResultSet will automatically be closed by the Statement when you do another query in the loop, because you use the same Statement object for all your queries (like I pointed out above). Therefore it will run fine for the first loop pass, but fail for every next pass. -
blablubbabc
Ok. So should I just create a new statement then? So I should create a new statement when executing that loop and close it when I’m done with it.
-
mrkirby153
Or first store all your «productId’s» from the ResultSet, in a list for example, and then call .redeemItem() for each of them.
- Thread Status:
-
Not open for further replies.
Share This Page
I faced this problem recently. As a part of closing some resources, I was closing resources in the finally block.
ResultSet resultSet; // class variable
...
...
Statement st = null;
try {
st = conn.createStatement();
resultSet = st.getGeneratedKeys();
} catch (Exception e) {
throw e;
} finally {
try {
if (st != null) st.close();
} catch (SQLException e) {
throw e;
}
}
As soon as I did this, I started to get the exception when I tried resultSet.hasNext();
java.sql.SQLException: Operation not allowed after ResultSet closed
My initial guess was I might have executed resultSet.close() somewhere. But it was not the case.
Problem
The actual problem is, ResultSet instance also saves underlying Statement. So, when the underlying Statment is closed (as done in the FINALLY block above), ResultSet is also closed. This causes the problem.
JavaDoc has clearly mentioned this.
When a Statement object is closed, its current ResultSet object, if one exists, is also closed.
Solution
So to fix the problem, you obviously cannot close the Statement instance untill you are done with ResultSet. Once you are done with ResultSet, you can close both ResultSet and Statement.
Вы не должны передавать ResultSet через общедоступные методы. Это подвержено утечке ресурсов, потому что вы вынуждены сохранять отчет и соединение открыто. Закрытие их неявно закрывает набор результатов. Но держать их открытыми приведет к тому, что они будут болтаться и заставить БД исчерпывать ресурсы, когда их слишком много.
Сопоставьте его с коллекцией Javabeans, как это, и верните его вместо:
public List<Biler> list() throws SQLException {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
List<Biler> bilers = new ArrayList<Biler>();
try {
connection = database.getConnection();
statement = connection.prepareStatement("SELECT id, name, value FROM Biler");
resultSet = statement.executeQuery();
while (resultSet.next()) {
Biler biler = new Biler();
biler.setId(resultSet.getLong("id"));
biler.setName(resultSet.getString("name"));
biler.setValue(resultSet.getInt("value"));
bilers.add(biler);
}
} finally {
if (resultSet != null) try { resultSet.close(); } catch (SQLException ignore) {}
if (statement != null) try { statement.close(); } catch (SQLException ignore) {}
if (connection != null) try { connection.close(); } catch (SQLException ignore) {}
}
return bilers;
}
Или, если вы уже на Java 7, просто используйте try-with-resources выражение, которое автоматически закрывает эти ресурсы
public List<Biler> list() throws SQLException {
List<Biler> bilers = new ArrayList<Biler>();
try (
Connection connection = database.getConnection();
PreparedStatement statement = connection.prepareStatement("SELECT id, name, value FROM Biler");
ResultSet resultSet = statement.executeQuery();
) {
while (resultSet.next()) {
Biler biler = new Biler();
biler.setId(resultSet.getLong("id"));
biler.setName(resultSet.getString("name"));
biler.setValue(resultSet.getInt("value"));
bilers.add(biler);
}
}
return bilers;
}
Кстати, вы не должны объявлять Connection, Statement и ResultSet как переменные экземпляра вообще (основная проблема безопасности потоков!) и не проглатывать SQLException в этой точке вообще ( вызывающий не будет знать, что возникла проблема), а также не закрывать ресурсы в том же try (если, например, закрытие результата закрывает исключение, то инструкция и соединение все еще открыты). Все эти проблемы исправлены в приведенных выше фрагментах кода.
Хорошо пытался понять это последние 2 дня.
Statement statement = con.createStatement();
String query = "SELECT * FROM sell";
ResultSet rs = query(query);
while (rs.next()){//<--- I get there operation error here
Это метод запроса.
public static ResultSet query(String s) throws SQLException {
try {
if (s.toLowerCase().startsWith("select")) {
if(stm == null) {
createConnection();
}
ResultSet rs = stm.executeQuery(s);
return rs;
} else {
if(stm == null) {
createConnection();
}
stm.executeUpdate(s);
}
return null;
} catch (Exception e) {
e.printStackTrace();
con = null;
stm = null;
}
return null;
}
Как исправить эту ошибку?
5 ответы
Трудно быть уверенным только из кода, который вы разместили, но я подозреваю, что ResultSet непреднамеренно закрывается (или stm используется повторно) внутри тела while поиска. Это вызовет исключение в начале следующей итерации.
Кроме того, вам необходимо убедиться, что в вашем приложении нет других потоков, которые потенциально могут использовать то же соединение с БД или stm объект.
Создан 07 июн.
ИМХО, вы должны сделать все, что вам нужно, с вашим ResultSet, прежде чем закрыть соединение.
Создан 07 июн.
есть несколько вещей, которые вам нужно исправить. Открытие соединения, выполнение запроса для получения rs, его закрытие и закрытие соединения — все должно выполняться в одной и той же функции, насколько это возможно. из вашего кода вы, кажется, используете переменную «con» в качестве глобальной переменной, что потенциально может вызвать проблему. вы не закрываете объект stm. или объект rs. этот код не работает слишком долго, даже если в нем нет ошибок. Ваш код должен быть таким:
if (stringUtils.isBlank(sql)){
throw new IllegalArgumentsException ("SQL statement is required");
}
Connection con = null;
PreparedStatement ps =null;
Resultset rs = null;
try{
con = getConnection();
ps = con.preparestatement(sql);
rs = ps.executeQuery();
processResults(rs);
close(rs);
close(ps);
close(con);
}catch (Execption e){
log.Exception ("Error in: {}", sql, e);
throw new RuntimeException (e);
}finally{
close(rs);
close(ps);
close(con);
}
Создан 07 июн.
использовать другой объект оператора во внутреннем цикле
Statement st,st1;
st=con.createStatement();
st1=con.createStatement();
//in Inner loop
while(<<your code>>)
{
st1.executeQuery(<<your query>>);
}
ответ дан 29 дек ’13, 17:12
Я знаю, что это запоздало на несколько лет, но я обнаружил, что синхронизация методов БД обычно избавляет от этой проблемы.
Создан 22 ноя.
Не тот ответ, который вы ищете? Просмотрите другие вопросы с метками
java
sql
select
resultset
or задайте свой вопрос.