2014-03-19 262 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

相关问题