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

标签 java mysql

我已经在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/

相关文章:

java - 通过 gmail 发送电子邮件的属性

java - Mockito:@Mock 对象何时初始化以及它调用哪个构造函数

MySQL - 如何在订单和组之后选择不同的行?

mysql - 在 Windows 中使用 mysqlbinlog 实用程序

mysql - 在 MySql 中生成伪列

java - 第二次替换全部不起作用

java - 我想获取数组的最后一行

java - eclipse ;封装方法 block

java - JPA多对一/一对多查询

mysql - 如何在android中将Mysql DB导入到SQlite中?