Forum Stats

  • 3,751,020 Users
  • 2,250,300 Discussions
  • 7,867,261 Comments

Discussions

DB Connection: Operation not allowed after ResultSet closed

User_AYF65
User_AYF65 Member Posts: 135 Red Ribbon
edited Jul 11, 2016 2:48PM in NetBeans

Hi,

I am trying to access a database using netBeans.I am using the 'select' query. I have got only one record. I am displaying its only two fields in the jTextField. I have a button (next) component. I have written its handler which is used to traverse the resultset. In the constructor i am connecting with the DB. When i am pressing the 'next' button first time, its displaying the two fields of db in the jTextfield. But when i am pressing the 'next' button again, i am getting the error, "Operation not allowed after ResultSet Closed".

My complete code is (the signature of constructor & handler is underlined):

package jdb1;

import java.sql.*;

/**

*

* @author HP

*/

public class Javadb1 extends javax.swing.JFrame {

private static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; 

private static final String DB_URL = "jdbc:mysql://localhost/test";

   //  Database credentials

private static final String USER = "root";

private static final String PASS = "z";

private Connection conn = null;

private Statement stmt = null;

String sql="";

ResultSet rs= null;

    /**

     * Creates new form Javadb1

     */

   public Javadb1() {

       

      try{

      //STEP 2: Register JDBC driver

      Class.forName("com.mysql.jdbc.Driver");

      //STEP 3: Open a connection

      System.out.println("Connecting to database...");

      conn = DriverManager.getConnection(DB_URL,USER,PASS);

      //STEP 4: Execute a query

      System.out.println("Creating statement...");

      stmt = conn.createStatement();

      sql = "SELECT name, owner FROM pet";

      rs = stmt.executeQuery(sql);

      }catch(SQLException se){

      //Handle errors for JDBC

      se.printStackTrace();

   }catch(Exception e){

      //Handle errors for Class.forName

      e.printStackTrace();

   }

   System.out.println("Goodbye!");

     

      initComponents();

    }

    /**

     * This method is called from within the constructor to initialize the form.

     * WARNING: Do NOT modify this code. The content of this method is always

     * regenerated by the Form Editor.

     */

    @SuppressWarnings("unchecked")

    // <editor-fold defaultstate="collapsed" desc="Generated Code">                         

    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();

        jNext = new javax.swing.JButton();

        jName = new javax.swing.JTextField();

        jOwner = new javax.swing.JTextField();

        jSex = new javax.swing.JTextField();

        jBirth = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jNext.setText("Next");

        jNext.addActionListener(new java.awt.event.ActionListener() {

            public void actionPerformed(java.awt.event.ActionEvent evt) {

                jNextActionPerformed(evt);

            }

        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);

        jPanel1.setLayout(jPanel1Layout);

        jPanel1Layout.setHorizontalGroup(

            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()

                .addContainerGap(155, Short.MAX_VALUE)

                .addComponent(jNext)

                .addContainerGap())

            .addGroup(jPanel1Layout.createSequentialGroup()

                .addGap(28, 28, 28)

                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)

                    .addComponent(jName)

                    .addComponent(jOwner)

                    .addComponent(jSex)

                    .addComponent(jBirth, javax.swing.GroupLayout.DEFAULT_SIZE, 94, Short.MAX_VALUE))

                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))

        );

        jPanel1Layout.setVerticalGroup(

            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

            .addGroup(jPanel1Layout.createSequentialGroup()

                .addGap(21, 21, 21)

                .addComponent(jNext)

                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)

                .addComponent(jName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)

                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)

                .addComponent(jOwner, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)

                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)

                .addComponent(jSex, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)

                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)

                .addComponent(jBirth, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)

                .addContainerGap(40, Short.MAX_VALUE))

        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());

        getContentPane().setLayout(layout);

        layout.setHorizontalGroup(

            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

            .addGroup(layout.createSequentialGroup()

                .addGap(67, 67, 67)

                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)

                .addContainerGap(113, Short.MAX_VALUE))

        );

        layout.setVerticalGroup(

            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

            .addGroup(layout.createSequentialGroup()

                .addGap(48, 48, 48)

                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)

                .addContainerGap(49, Short.MAX_VALUE))

        );

        pack();

    }// </editor-fold>                       

    private void jNextActionPerformed(java.awt.event.ActionEvent evt) {                                     

        // TODO add your handling code here:

        try{

        if(rs.next()){

             String name = rs.getString("name");

             String owner = rs.getString("owner");

             jName.setText(name);

             jOwner.setText(owner);

            

        }

        else {

            rs.close();

            stmt.close();

            conn.close();

            }

        }catch(SQLException se){

      //Handle errors for JDBC

      se.printStackTrace();

   }catch(Exception e){

      //Handle errors for Class.forName

      e.printStackTrace();

   }

       finally{

      //finally block used to close resources

      try{

         if(stmt!=null)

            stmt.close();

      }catch(SQLException se2){

      }// nothing we can do

      try{

         if(conn!=null)

            conn.close();

      }catch(SQLException se){

         se.printStackTrace();

      }//end finally try

      try{

         if(rs!=null)

            rs.close();

      }catch(SQLException se){

         se.printStackTrace();

      }//end fina*/

   }

//end try

    }                                    

    /**

     * @param args the command line arguments

     */

    public static void main(String args[]) {

        /* Set the Nimbus look and feel */

        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">

        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.

         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html

         */

        try {

            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {

                if ("Nimbus".equals(info.getName())) {

                    javax.swing.UIManager.setLookAndFeel(info.getClassName());

                    break;

                }

            }

        } catch (ClassNotFoundException ex) {

            java.util.logging.Logger.getLogger(Javadb1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);

        } catch (InstantiationException ex) {

            java.util.logging.Logger.getLogger(Javadb1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);

        } catch (IllegalAccessException ex) {

            java.util.logging.Logger.getLogger(Javadb1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);

        } catch (javax.swing.UnsupportedLookAndFeelException ex) {

            java.util.logging.Logger.getLogger(Javadb1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);

        }

        //</editor-fold>

        /* Create and display the form */

        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {

                new Javadb1().setVisible(true);

            }

        });

    }

    // Variables declaration - do not modify                    

    private javax.swing.JTextField jBirth;

    private javax.swing.JTextField jName;

    private javax.swing.JButton jNext;

    private javax.swing.JTextField jOwner;

    private javax.swing.JPanel jPanel1;

    private javax.swing.JTextField jSex;

    // End of variables declaration                  

}


The error messages are:

java.sql.SQLException: Operation not allowed after ResultSet closed

  at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:910)

  at com.mysql.jdbc.ResultSet.checkClosed(ResultSet.java:666)

  at com.mysql.jdbc.ResultSet.next(ResultSet.java:7274)

  at jdb1.Javadb1.jNextActionPerformed(Javadb1.java:149)

  at jdb1.Javadb1.access$000(Javadb1.java:12)

  at jdb1.Javadb1$1.actionPerformed(Javadb1.java:88)

  at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)

  at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)

  at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)

  at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)

  at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)

  at java.awt.Component.processMouseEvent(Component.java:6535)

  at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)

  at java.awt.Component.processEvent(Component.java:6300)

  at java.awt.Container.processEvent(Container.java:2236)

  at java.awt.Component.dispatchEventImpl(Component.java:4891)

  at java.awt.Container.dispatchEventImpl(Container.java:2294)

  at java.awt.Component.dispatchEvent(Component.java:4713)

  at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)

  at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)

  at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)

  at java.awt.Container.dispatchEventImpl(Container.java:2280)

  at java.awt.Window.dispatchEventImpl(Window.java:2750)

  at java.awt.Component.dispatchEvent(Component.java:4713)

  at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)

  at java.awt.EventQueue.access$500(EventQueue.java:97)

  at java.awt.EventQueue$3.run(EventQueue.java:709)

  at java.awt.EventQueue$3.run(EventQueue.java:703)

  at java.security.AccessController.doPrivileged(Native Method)

  at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)

  at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)

  at java.awt.EventQueue$4.run(EventQueue.java:731)

  at java.awt.EventQueue$4.run(EventQueue.java:729)

  at java.security.AccessController.doPrivileged(Native Method)

  at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)

  at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)

  at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)

  at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)

  at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)

  at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)

  at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)

  at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)



Some body please guide me.


Zulfi.