2014-03-19 48 views
2

爲什麼你認爲這個函數總是讓我空? 使用另一個具有相同代碼結構的登錄程序,它工作得非常好。 我DBURL爲jdbc:mysql的://本地主機:8889 /數據庫java.sql.SQLException:訪問被拒絕用戶'root'@'localhost'(使用密碼:YES)

public String retrieveUserPassword(String userName, String password) { 

    String query = "SELECT UserPassword FROM Access where UserName='"+userName+"'"; 
    String dbresult=null; //this might be the problem, but I must define it 

    try { 
     Class.forName("com.mysql.jdbc.Driver"); 

    }catch (ClassNotFoundException ex1) { 

     System.out.println("Driver could not be loaded: " + ex1); 
     Logger.getLogger(DatabaseModel.class.getName()).log(Level.SEVERE, null, ex1); 
    } 
    try { 

      //These are private variables declared at the top of the class 
      //and used by various functions 
      con = DriverManager.getConnection(DatabaseURL, userName, password); 
      st = con.createStatement(); 
      rs = st.executeQuery(query); 

      if(rs.next()){ 

       dbresult= rs.getString(3); 
      } 

    }catch (SQLException e) { 

     e.printStackTrace(); 
    }  

    return dbresult; 

} 

Access表由三列: 用戶名,用戶名,userPassword的

+0

下面的命令並不標題回答這個問題? –

+0

調試並檢查查詢是否實際返回任何值。即「if(rs.next())'爲真。 –

+0

@達維達。一個。正如我所說的,代碼是正確的,因爲我在另一個程序中嘗試複製和粘貼,而我沒有這個問題。數據庫始終授予對root用戶的訪問權限。 – QGA

回答

7

值java.sql.SQLException:訪問拒絕用戶'root'@'localhost'(使用密碼:是)

正如您所提到的,問題在於與數據庫本身建立連接。聲明

con = DriverManager.getConnection(DatabaseURL, userName, password); 

拋出其在

catch (SQLException e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 

之後要返回dbresult您已初始化爲null(你必須,因爲它是一個局部變量)陷入異常。所以問題是你無法連接到你的數據庫由於身份驗證。

在您的機器在哪裏(在烏拉圭回合的情況下本地主機)上運行,從控制檯

GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' IDENTIFIED BY 'root' WITH GRANT OPTION; 
+0

我愛你,但是,我沒有得到它爲什麼它與我以前的代碼沒有授權訪問 – QGA

相關問題