JDBC Access denied for user 'root'@'localhost'

廉价感情. 提交于 2019-12-25 04:23:11

问题


This is an error for me. I have used proper password as this is what I type when I start MySQL.

DefaultTableModel dtm=(DefaultTableModel) jTable1.getModel();
dtm.setRowCount(0);
try{
    Class.forName("java.sql.Driver");
    Connection c=DriverManager.getConnection("jdbc:mysql://localhost/shashvat","root","1234");
    Statement s=c.createStatement();       
    ResultSet r=s.executeQuery("select * from phasetests;");

    while(r.next()){
        Object arr[]={r.getString(1),r.getString(2),r.getString(3),r.getString(4)};
        dtm.addRow(arr);
    }
}catch(Exception e){
System.out.println(e.getMessage());   
}

The Exception Message:

Access denied for user 'root'@'localhost' (using password: YES)

I have tried this too: https://stackoverflow.com/a/17908407/5036731

The problem still persists. Please help.


回答1:


EDIT: Your code should be something like this.

DefaultTableModel dtm=(DefaultTableModel) jTable1.getModel();
dtm.setRowCount(0);
try{ 
    //Class.forName("java.sql.Driver"); This is wrong
    Class.forName("com.mysql.jdbc.Driver"); // Declare it like this..
    Connection c=DriverManager.getConnection("jdbc:mysql://localhost:3306/shashvat","root","1234"); // port number was missing
    Statement s=c.createStatement();       
    ResultSet r=s.executeQuery("select * from phasetests;");

    while(r.next()){
        Object arr[]={r.getString(1),r.getString(2),r.getString(3),r.getString(4)};
        dtm.addRow(arr);
    } 
}catch(Exception e){
System.out.println(e.getMessage());   
} 

See the code I mentioned here is working. I checked it locally. The problem should be with the password or schema access for which you can refer following.

Access Denied for User 'root'@'localhost' (using password: YES) - No Privileges?

If it's a problem with privileges. Grant all privileges to root by executing following command.

GRANT ALL PRIVILEGES ON shashvat.* TO 'root'@'localhost' IDENTIFIED BY 'root'

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)




回答2:


Please use below mentioned syntax

   Connection c =DriverManager.getConnection("jdbc:mysql"+"://"+host+":"+port+"/"+db,"root","pass");



回答3:


Just correct your Driver name to com.mysql.jdbc.Driver and add host with port localhost:3306



来源:https://stackoverflow.com/questions/40354647/jdbc-access-denied-for-user-rootlocalhost

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!