This question already has answers here:
What is a NullPointerException, and how do I fix it?
                                
                                    (12个答案)
                                
                        
                                3年前关闭。
            
                    
我正在尝试从MySQL数据库检查用户名和密码,方法CheckFromDB()
从AccessoDB类调用方法,以便与数据库建立连接。

我发现问题显示在我创建该语句的那一刻
AccessoDB.selectFixedQuery()方法。

这是我使用的代码:

   public boolean checkFromDB(){
    AccessoDB accesso = new AccessoDB();
    accesso.openConnectionToDB();
    ResultSet rs = accesso.selectFixedQuery("SELECT * FROM user WHERE nome = "+this.username+" && pwd = "+this.password);
    String uname_db = "", pwd_db = "";
    try {
        while (rs.next())
        {
            uname_db=rs.getString("nome");
            System.out.println(uname_db);
            pwd_db = rs.getString("pwd");
        }
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    accesso.closeConnectionToDB();
    boolean res = false;
    res = uname_db.equals(this.username)&& pwd_db.equals(this.password);
    return res;
}


类AccessoDB中的方法selectFixedQuery:

    public ResultSet selectFixedQuery(String p_sqlQuery) {

    // istantiate a resultSet
    ResultSet rs = null;
    Statement st = null;
    try {

        // create statement associated to the query
        st = dbConnection.createStatement();

        // esegue la query
        rs = st.executeQuery(p_sqlQuery);

    } catch (SQLException e) {
        Logger.println("ANALISI DELL'ERRORE");
        Logger.println(e.getMessage());
        Logger.println("FINE ANALISI DELL'ERRORE");
    }

    // ritorna il risultato
    return rs;
} // end method

    public void openConnectionToDB() {

    try {
        // allocazione del driver (antico)
        Class.forName(dbDriverName).newInstance();

        // creazione della connessione
        dbConnection = DriverManager.getConnection(connectionString,
                                                    dbUsername,
                                                    dbPassword);
    }
    // serve solo se si usa il Driver
    catch (ClassNotFoundException cnfe) {
        Logger.println("Driver not found!");
        Logger.println(cnfe.getMessage());
    }
    catch (SQLException sqle) {
        Logger.println("Conessione al DB non riuscita!");
        Logger.println(sqle.getMessage());
    }
    catch (Exception e) {
        // gestire errore insolito
        Logger.println(e.getMessage());
    }
} // end method

最佳答案

openConnectionToDB()应该返回dbConnection对象,现在您的连接对象在方法调用中丢失了。存储并将其传递回您的selectFixedQuery()方法

09-16 01:56