gpt4 book ai didi

java - 无法以编程方式连接到 mysql

转载 作者:行者123 更新时间:2023-11-29 10:19:03 25 4
gpt4 key购买 nike

我已经在linux机器上安装了mysql(mariadb)。我创建了一个用户“newuser”,例如:

CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON * . * TO 'newuser'@'localhost';

当我这样做时:

select user,password from user;

我可以看到:

+--------------+-------------------------------------------+
| user | password |
+--------------+-------------------------------------------+
| root | *password |
| newuser | *password |
+--------------+-------------------------------------------+

当我执行这个命令时:

select user();

+----------------+
| user() |
+----------------+
| root@localhost |
+----------------+

我正在尝试使用 java 连接到我的数据库,但出现以下异常:

java.sql.SQLException: Cannot create connection:Access denied for user 'newuser'@'localhost' (using password: YES)

+------------------------------------------------------------------------------------------------------------------------------------------------+
| Grants for newuser@localhost |
+------------------------------------------------------------------------------------------------------------------------------------------------+
| GRANT ALL PRIVILEGES ON *.* TO 'newuser'@'localhost' IDENTIFIED BY PASSWORD '*7ABDF971526E9441B919C9FE77D50DB0363B3509' WITH GRANT OPTION |
+------------------------------------------------------------------------------------------------------------------------------------------------+

连接数据库的Java代码:

try {
Class.forName("com.mysql.jdbc.Driver");
// Connection connection = DriverManager.getConnection(connectionString);
Connection connection = DriverManager.getConnection("jdbc:mariadb://localhost:3306/iot?autoReconnect=true","newuser","password");
System.out.println("Connected --->" + connection);
return connection;
} catch (SQLException e) {
throw new SQLException("Cannot create connection:" + e.getMessage());
}

谁能帮我解决我所缺少的东西?

最佳答案

尝试连接到mysql并执行

update user set host = '%' where user = 'newuser';
flush privileges;

再次尝试连接。如果你成功了那么(正如我怀疑的那样)你没有在与 mysql 相同的机器上运行代码。你需要找到本地机器的ip(linux上是ifconfig,windows上是ipconfig)并执行

update user set host = 'xxx.xxx.xxx.xxx.' where user = 'newuser';
flush privileges;

仅允许来自您的 IP (xxx.xxx.xxx.xxx) 的连接。

要恢复更改,请执行

update user set host = 'localhost' where user = 'newuser';
flush privileges;

关于java - 无法以编程方式连接到 mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49655116/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com