java.lang.NullPointerException从MySQL查询创建语句

时间:2016-04-18 09:15:22

标签: java mysql nullpointerexception

我正在尝试从MySQL数据库检查用户名和密码,方法CheckFromDB() 从AccessoDB类调用方法,以便与DB建立连接。

我知道问题显示在我创建声明的那一刻 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

1 个答案:

答案 0 :(得分:0)

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