作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我已经在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/
我是一名优秀的程序员,十分优秀!