executeQuery NullPointerException错误

时间:2018-07-28 21:32:59

标签: java sql netbeans nullpointerexception executequery

我对此很介意,这可能就是为什么我在尝试做一些非常简单的事情时遇到此错误。

我只想获取当前的用户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!");
    }
}                             

“ ResultSet rss = sta.executeQuery();”是NullPointerException部分。

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

谢谢

1 个答案:

答案 0 :(得分:0)

您初始化

private PreparedStatement sta=null;

因此,stanull,并给您NullPointerException

您可以根据自己的项目尝试一些尝试,

sta = new PreparedStatement()

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