2016-04-18 170 views
0

我試圖從MySQL數據庫檢查用戶名和密碼,方法CheckFromDB() 從AccessoDB類調用方法,以建立與數據庫的連接。java.lang.NullPointerException從MySQL查詢創建語句

我得到的問題顯示,在我打包 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; 
} 

方法selectFixedQuery類AccessoDB:

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 
+0

提供您的openConnectionToDB()方法和堆棧跟蹤。 – Janath

+0

我加了openConnectionToDB(),抱歉什麼是堆棧跟蹤?錯誤信息? – Argentina

+0

一旦你發現異常,你可以按如下方式處理堆棧跟蹤。 e.printStackTrace(); – Janath

回答

0

openConnectionToDB()應該返回的DbConnection對象,現在你的連接對象丟失在方法調用中。存儲並將其傳回給您的selectFixedQuery()方法

+0

不。因爲它使用相同的Accesso對象。 – Janath

+0

他可能使用了代碼中未顯示的全局類變量 –