java - homeandlearn数据库教程 - rs.Next空指针异常

时间:2013-10-11 16:21:37

标签: java database

我正在阅读以下教程。我无法从数据库中调用下一个项目。

http://www.homeandlearn.co.uk/java/database_scrolling_buttons.html

尽可能减少我的课程,使问题更容易阅读..

package Employees;

import java.sql.Connection;
imports ... etc

在顶部导入然后构造函数被称为

public class Workers extends javax.swing.JFrame {

    Connection con;
    Statement stmt;
    ResultSet rs;

    /**
     * Creates new form Workers
     */
    public Workers() {
        initComponents();
        DoConnect();
    }

    cont..
}

这是DoConnect方法 - 这可以正常工作,因为它设置了变量,你可以在表单上看到它们。

   public void DoConnect(){

        try {
            String host   = "jdbc:derby://localhost:1527/Employees";
            String uName  = "robert";
            String uPass  = "robert";

            Connection con = DriverManager.getConnection(host, uName, uPass);

            String SQL = "SELECT * FROM APP.WORKERS";

            Statement stmt = con.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE  );
            ResultSet rs = stmt.executeQuery( SQL);

            rs.next();

            int    id_col     = rs.getInt("ID");
            String first_name = rs.getString("First_Name");
            String last_name  = rs.getString("Last_Name");
            String job        = rs.getString("Job_Title");


            // DISPLAY THE FIRST RECORD IN THE TEXT FIELDS
            textID.setText(Integer.toString(id_col));
            textFirstName.setText(first_name);
            //   etc... this works ok
        }
        catch(SQLException err){
            JOptionPane.showMessageDialog(Workers.this, err.getMessage());
        }
    }

然而,这是我得到我的错误的功能。当我单击下一个按钮时,它应该从数据库中获取下一个项目。但是,我不认为我正在使用rs正确的方式 - 我按照教程?我不认为它喜欢rs.Next()方法吗?

以下是下一个按钮的代码

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

    try 
    {
        if ( rs.next() ) { // this is the line where I get the error

        }
        else 
        {
            rs.previous( );
            JOptionPane.showMessageDialog(Workers.this, "End of File");
        }
    }
    catch (SQLException err) {
        JOptionPane.showMessageDialog(Workers.this, err.getMessage());
    }        
}  

当我按下一步时,我收到以下错误。

    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
        at Employees.Workers.buttonNextActionPerformed(Workers.java:164)
        at Employees.Workers.access$200(Workers.java:18)
             .. 

不确定我需要做些什么来解决它。非常感谢。

以下是所要求的完整代码...... Workers.java

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Employees;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.ResultSet;
import javax.swing.JOptionPane;

/**
 *
 * @author davidsonr
 */
public class Workers extends javax.swing.JFrame {

    Connection con;
    Statement stmt;
    ResultSet rs;

    /**
     * Creates new form Workers
     */
    public Workers() {
        initComponents();
        DoConnect();
    }

    /**
     * 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();
        textID = new javax.swing.JTextField();
        textFirstName = new javax.swing.JTextField();
        textLastName = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        textJobTitle = new javax.swing.JTextField();
        buttonFirst = new javax.swing.JButton();
        buttonPrevious = new javax.swing.JButton();
        buttonNext = new javax.swing.JButton();
        buttonLast = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        textID.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                textIDActionPerformed(evt);
            }
        });

        jLabel1.setText("Job Title");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(textID))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(textFirstName, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(textLastName, javax.swing.GroupLayout.DEFAULT_SIZE, 232, Short.MAX_VALUE))
                    .addComponent(textJobTitle))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(textID, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(textFirstName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(textLastName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(textJobTitle, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addContainerGap(38, Short.MAX_VALUE))
        );

        buttonFirst.setText("First");
        buttonFirst.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonFirstActionPerformed(evt);
            }
        });

        buttonPrevious.setText("Previous");

        buttonNext.setText("Next");
        buttonNext.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonNextActionPerformed(evt);
            }
        });

        buttonLast.setText("Last");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(buttonFirst)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(buttonPrevious)
                        .addGap(104, 104, 104)
                        .addComponent(buttonNext)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(buttonLast)))
                .addContainerGap(30, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(buttonFirst)
                    .addComponent(buttonPrevious)
                    .addComponent(buttonNext)
                    .addComponent(buttonLast))
                .addContainerGap(160, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                        

    private void textIDActionPerformed(java.awt.event.ActionEvent evt) {                                       
        // TODO add your handling code here:
    }                                      

    private void buttonFirstActionPerformed(java.awt.event.ActionEvent evt) {                                            
        // TODO add your handling code here:
    }                                           



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

        try 
        {
            if ( rs.next() ) { // this is the line where I get the error

            }
            else 
            {
                rs.previous( );
                JOptionPane.showMessageDialog(Workers.this, "End of File");
            }
        }
        catch (SQLException err) {
            JOptionPane.showMessageDialog(Workers.this, err.getMessage());
        }        
    }                                          


    public void DoConnect(){


        try {

            String host   = "jdbc:derby://localhost:1527/Employees";
            String uName  = "robert";
            String uPass  = "robert";

            Connection con = DriverManager.getConnection(host, uName, uPass);

            String SQL = "SELECT * FROM APP.WORKERS";

            Statement stmt = con.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE  );
            ResultSet rs = stmt.executeQuery( SQL);

            rs.next();

            int    id_col     = rs.getInt("ID");
            String first_name = rs.getString("First_Name");
            String last_name  = rs.getString("Last_Name");
            String job        = rs.getString("Job_Title");

            // DISPLAY THE FIRST RECORD IN THE TEXT FIELDS
            textID.setText(Integer.toString(id_col));
            textFirstName.setText(first_name);
            textLastName.setText(last_name);
            textJobTitle.setText(job);


        }
        catch(SQLException err){
            JOptionPane.showMessageDialog(Workers.this, err.getMessage());
        }



    }

    /**
     * @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(Workers.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Workers.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Workers.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Workers.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 Workers().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify                     
    private javax.swing.JButton buttonFirst;
    private javax.swing.JButton buttonLast;
    private javax.swing.JButton buttonNext;
    private javax.swing.JButton buttonPrevious;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JTextField textFirstName;
    private javax.swing.JTextField textID;
    private javax.swing.JTextField textJobTitle;
    private javax.swing.JTextField textLastName;
    // End of variables declaration                   
}

2 个答案:

答案 0 :(得分:4)

在DoConnect()中,你会影响你的'rs'变量。 写下这个:

 rs = stmt.executeQuery( SQL); //without 'ResultSet'
 rs.next();

答案 1 :(得分:0)

确保在buttonNextActionPerformed(Workers.java:164)执行之前,无论如何rs必须初始化。您按照执行步骤和代码进行确认。