SQLException:用户'root'@'localhost'拒绝访问

时间:2013-10-31 22:45:53

标签: java mysql

我在Mac上使用帐户(root,mypassword)安装mysql。我可以通过此帐户使用“MySQL Query Browser”连接到数据库。但是,当我尝试通过Java驱动程序连接时,我有一个例外: java.sql.SQLException:用户'root'@'localhost'拒绝访问(使用密码:YES)

我知道很多人和我有同样的问题。我在https://stackoverflow.com/上阅读并尝试了很多相关主题。但它无法解决我的问题。 你能帮帮我吗?

先谢谢你。

这是我的代码

System.out.println("-------- MySQL JDBC Connection Testing ------------");

try {
    Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
    System.out.println("Where is your MySQL JDBC Driver?");
    e.printStackTrace();
    return;
}

System.out.println("MySQL JDBC Driver Registered!");
Connection connection = null;

try {
    connection = (Connection) DriverManager
    .getConnection("jdbc:mysql://localhost:3306/test","root", "mypassword");

} catch (SQLException e) {
    System.out.println("Connection Failed! Check output console");
    e.printStackTrace();
    return;
}

if (connection != null) {
    System.out.println("You made it, take control your database now!");
} else {
    System.out.println("Failed to make connection!");
}

1 个答案:

答案 0 :(得分:0)

 create user 'myUser'@'*' identified by 'mypassword';
 grant all privileges on test.* to 'myUser'@'%' identified by 'mypassword' with grant option;
 flush privileges;

在你的mysql实例上,试试这三行。然后在Java代码中,将登录名从root更改为myUser。