【问题标题】:executeQuery NullPointerException Error [duplicate]executeQuery NullPointerException 错误 [重复]
【发布时间】:2019-01-05 14:37:50
【问题描述】:

我在这方面是初学者,这可能是我在尝试做一些非常简单的事情时遇到此错误的原因。

我只想获取当前用户 ID 并在其他类中使用它。但我收到 ExecuteQuery() 行的 NullPointerException 错误。

让我分享代码:

public class LoginPage extends javax.swing.JFrame {

private Connection conn=null;
private ResultSet rs=null;
private PreparedStatement pst=null;
private PreparedStatement sta=null;

ConnectionDB connect=new ConnectionDB();


public LoginPage() {
    initComponents();
}

public void getCurrentUser(){
    try{
            PreparedStatement c;
            conn=connect.getConnection();
            PreparedStatement stmt = conn.prepareStatement("SELECT * FROM users where Mail=?");
            stmt.setString(1, lMail.getText());
            ResultSet rss=sta.executeQuery();
            if(rss.next()){
                int CurrentUserID=rss.getInt("ID");
            }
        }
        catch(SQLException ex){
            System.out.println("SQL Exception Error!1");
        }
}

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

    String sql="SELECT * from users where Mail=? and Password=?";
    try{
        conn=connect.getConnection();
        pst=conn.prepareStatement(sql);
        pst.setString(1,lMail.getText());
        pst.setString(2,lPass.getText());
        rs=pst.executeQuery();

    if(rs.next()){
        getCurrentUser();        
        JOptionPane.showMessageDialog(null, "Welcome!");
        new ListPage().setVisible(true);
        dispose();
    }
    else
    {
        JOptionPane.showMessageDialog(null, "Wrong mail-password combination!");
        lPass.setText("");
    }
    }
    catch(SQLException ex){
        System.out.println("SQL Exception Error!");
    }
}                             

"结果集 rss=sta.executeQuery();"是 NullPointerException 部分。

我花了几个小时来解决这个问题,但我不能,所以我需要你的帮助。

谢谢

【问题讨论】:

  • 你有这个:private PreparedStatement sta=null;你应该在那个方法中使用它之前初始化它,它仍然是null
  • 你永远不会初始化sta。您可能想使用stmt

标签: java sql netbeans nullpointerexception executequery


【解决方案1】:

你初始化

private PreparedStatement sta=null;

因此,sta 是 null 并给你NullPointerException。

你可以根据你的项目尝试一些东西,

sta = new PreparedStatement()

或者

ResultSet rss = stmt.executeQuery(); //stmt instead of sta

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-03
    • 2019-10-13
    • 1970-01-01
    • 1970-01-01
    • 2012-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多