因此,这是一个从数据库中获取数据的Jmenu。错误是,当按下“视图定义”按钮时,没有触发相应的事件。理想情况下,当用户从Jmenu中选择一个项目并按下此按钮时,将再次连接数据库以基于从Jmenu中选择的项目从数据库中获取相应的值。但是声明

ResultSet rs=st.executeQuery("select Metric_Name from Metrics where Metrics.Metric_Name='NAA'");


似乎从不执行并抛出错误

datajava.lang.NullPointerException


是什么引起此错误以及如何解决此错误?这是我的代码:

public class ListModelExample extends JPanel {

  JList list;

  DefaultListModel model;

  public ListModelExample() {
    setLayout(new BorderLayout());
    model = new DefaultListModel();
    list = new JList(model);
    JScrollPane pane = new JScrollPane(list);
    JButton addButton = new JButton("View Definition");

     Connection con;
      ResultSet rs;
      Statement st = null;

    try {

        File dbFile = new File("executive_db.accdb");
        String path = dbFile.getAbsolutePath();
        con = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)}; DBQ= " + path);
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
       st = con.createStatement();


       }
    catch (Exception e)
    {
JOptionPane.showMessageDialog(null,"Failed to Connect to Database","Error Connection", JOptionPane.WARNING_MESSAGE);
System.exit(0);
   }


 try {
     model.clear();
     rs=st.executeQuery("select Metric_Name from Metrics");
     while (rs.next())
     {

         model.addElement(rs.getString("Metric_Name"));
     }

    }
 catch (Exception e)
    {
     System.out.println("Error in fetching data");
    }
   addButton.addActionListener(new ActionListener() {
      Statement st;

    public void actionPerformed(ActionEvent e) {

          String def = "";


          try {

                 model.clear();
                 st = null;
                 System.out.println("came here");
                 ResultSet rs=st.executeQuery("select Metric_Name from Metrics where Metrics.Metric_Name='NAA'");
                 System.out.println("came here too");
                 while (rs.next())
                 {

                     def = rs.getString("Metric_Name");

                     System.out.println(def);
                   //  model.addElement(rs.getString("Metric_Name"));
                 }

                }
             catch (Exception e1)
                {
                 System.out.println("Error in fetching data"+e1);
                }
          System.out.println(def);
          JOptionPane.showMessageDialog(null, def, "Error", JOptionPane.ERROR_MESSAGE);
      /*  model.addElement("Element " + counter);
        counter++;*/
      }
    });

    add(pane, BorderLayout.NORTH);
    add(addButton, BorderLayout.WEST);

  }

  public static void main(String s[]) {
    JFrame frame = new JFrame("List of Metrics used");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setContentPane(new ListModelExample());
    frame.setSize(260, 200);
    frame.setVisible(true);
  }
}


这是我执行e1.printStackTrace()时遇到的错误。
我的代码中的第94行是

ResultSet rs=st.executeQuery("select Metric_Name from Metrics where Metrics.Metric_Name='NAA'");




java.lang.NullPointerException
    at ListModelExample$1.actionPerformed(ListModelExample.java:94)
    at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
    at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
    at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
    at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Source)
    at java.awt.Component.processMouseEvent(Unknown Source)
    at javax.swing.JComponent.processMouseEvent(Unknown Source)
    at java.awt.Component.processEvent(Unknown Source)
    at java.awt.Container.processEvent(Unknown Source)
    at java.awt.Component.dispatchEventImpl(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
    at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
    at java.awt.Container.dispatchEventImpl(Unknown Source)
    at java.awt.Window.dispatchEventImpl(Unknown Source)
    at java.awt.Component.dispatchEvent(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$400(Unknown Source)
    at java.awt.EventQueue$2.run(Unknown Source)
    at java.awt.EventQueue$2.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
    at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.AccessControlContext$1.doIntersectionPrivilege(Unknown Source)Error in fetching datajava.lang.NullPointerException


    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)

最佳答案

                 st = null;
                 System.out.println("came here");
                 ResultSet rs=st.executeQuery("select Metric_Name from Metrics where Metrics.Metric_Name='NAA'");


我在上面的代码中注意到这一部分,它将确实导致空指针。

要解决此问题,请将此“ st”的声明作为主类的字段或成员变量(ListModelExample)。并在监听器中删除st = null和'Statement = st'成员变量声明。

    File dbFile = new File("executive_db.accdb");
    String path = dbFile.getAbsolutePath();
    con = DriverManager.getConnection("jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)}; DBQ= " + path);
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
   st = con.createStatement();

10-07 18:57