Basically I’m trying to loop through my database and display all of the information inside. I understand the concept that but my implementation is clearly wrong as Tomcat keeps giving me the the following error:
Root cause:
javax.servlet.ServletException: Operation not allowed after ResultSet closed
Any help would be much appreciated. I know the problem is with my while loop but my knowledge is limited and I cannot spot the changes I need to make. Please feel free to change the code.
<%@ page import="java.sql.*" %>
<%
String connectionURL = "jdbc:mysql://addr.to.db:3306/dbname";
Connection connection = null;
Statement statement = null;
ResultSet rs = null;
%>
<html>
<head>
<title>JSP Server Response</title>
</head>
<body>
<h1>JSP Server Response:</h1>
<!--Get information from HTML form for manipulation-->
<%
String songName = request.getParameter("newSongName");
String artistName = request.getParameter("newArtistName");
String password = request.getParameter("pass");
String radioResults = request.getParameter("dbIO");
%>
<%
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(connectionURL, "userName", "password");
statement = connection.createStatement();
String query = "SELECT * FROM song_info;";
rs = statement.executeQuery(query);
//Add or Delete Information from DB
if(radioResults.equalsIgnoreCase("insert"))
{
statement.executeUpdate("INSERT INTO song_info (songTitle, artistName) VALUES ('"+artistName+"','"+songName+"')");
}
else if(radioResults.equalsIgnoreCase("delete"))
{
statement.executeUpdate("DELETE FROM song_info WHERE artistName='"+songName+"'");
}
%>
<table>
<tr>
<th>Song Name</th><th>Artist Name</th>
</tr>
<% while(rs.next()){ %>
<tr>
<td align=center> <%= rs.getString("songTitle")%></td>
<td align=center> <%= rs.getString("artistName")%></td>
</tr>
<%}%>
</table>
<%
rs.close();
statement.close();
connection.close();
%>
Information Submitted to Server:
Artist Name: <%=songName%> <br />
Song Name: <%=artistName%> <br />
Password: <%=password%><br />
Radio Button Selection: <%=radioResults%><br /><br />
Password Correct:
</body>
</html>
The problem is that you are using the same
Statementobject to execute multiple queries. If you re-use theStatement, then any resources likeResultSetfrom a previous execution are closed.The solution is either to re-order the query (like you did in your own answer), or to use separate
Statementobjects for the query and the updates.Also your current code exposes you to SQL injection. Please use
PreparedStatementwith parametrized queries. This will protect you from most – if not all – SQL injection attacks.