Invalid Cursor State - Please Help
843854Mar 8 2002 — edited Mar 12 2002Only when a record is not found in the following code I get an Invalid Cursor State error. I learned from the previous forum questions that the problem can be solved by doing
while (rs.next())
{...}
rs.close();
but I am not sure how to apply that to my code. I tried numerous combinations, but the else statement seems to be hard to go about. Thanks in advance! Here is the code:
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
import javax.swing.*;
public class FindRecord implements ActionListener {
private ScrollingPanel fields;
private JTextArea output;
private Connection connection;
public FindRecord( Connection c, ScrollingPanel f,
JTextArea o )
{
connection = c;
fields = f;
output = o;
}
public void actionPerformed( ActionEvent e )
{
try {
if ( ( !fields.album.getText().equals( "" ) ) &
( !fields.artist.getText().equals( "" ) ) )
{
Statement statement = connection.createStatement();
String query = "SELECT * FROM CDs " +
"WHERE album = '" +
fields.album.getText() + "' AND artist = '" +
fields.artist.getText() + "'";
output.append( "\nSending query: " +
connection.nativeSQL( query )
+ "\n" );
ResultSet rs = statement.executeQuery( query );
display( rs );
output.append( "\nQuery successful\n" );
statement.close();
}
else
{
if ( fields.album.getText().equals( "" ) )
fields.album.setText("You must " +
"specify album name." );
if ( fields.artist.getText().equals( "" ) )
fields.artist.setText("You must " +
"specify artist name." );
}
}
catch ( SQLException sqlex ) {
sqlex.printStackTrace();
output.append( sqlex.toString() );
}
}
// Display results of query. If rs is null
public void display( ResultSet rs )
{
try {
rs.next();
int recordNumber = rs.getInt( 1 );
if ( recordNumber != 0 ) {
fields.catalogNumber.setText( String.valueOf( recordNumber));
fields.album.setText( rs.getString( 2 ) );
fields.artist.setText( rs.getString( 3 ) );
fields.label.setText( rs.getString( 4 ) );
fields.releaseDate.setText( rs.getString( 5 ) );
}
else
{
output.append( "\nNo record found\n" );
JOptionPane.showMessageDialog(
null, "No record found.",
"CD Collection Database",
JOptionPane.PLAIN_MESSAGE );
}
}
catch ( SQLException sqlex ) {
sqlex.printStackTrace();
output.append( sqlex.toString() );
}
}
}