【问题标题】:failed to connect to mysql database using java [duplicate]无法使用java连接到mysql数据库[重复]
【发布时间】:2019-08-20 03:14:41
【问题描述】:

我正在尝试连接到 MySQL 数据库并在我的 java 代码中使用 sql 语句获取一些数据。但我无法连接到我的数据库并出现以下 SQL 异常。

错误:java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)

我的java代码如下:

Mysql_connecter.java

package mysql_connecter;

import java.sql.*;
/**
 *
 * @author kass
 */
public class Mysql_connecter 
{
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) 
    {
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            System.out.println("connecting.....");
            try (Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb","user","password")) 
            {
                System.out.println("connected to mysql DB");
                Statement stmt=con.createStatement();

                ResultSet rs=stmt.executeQuery("select * from my_table");

                while(rs.next())
                {
                    System.out.println(rs.getInt(1)+"  "+rs.getString(2)+"  "+rs.getString(3));
                }
            }
            catch(SQLException e)
            { 
                System.out.println("ERROR: ["+e+"]");
            }
        }
        catch(ClassNotFoundException e)
        { 
            System.out.println(e);
        }
    } 
}

我已将 mysql jdbc 驱动程序添加到我的库路径中。我可以在我的代码中遗漏一些东西吗?

【问题讨论】:

  • 请尝试使用 PHPMyAdmin 或 Heidisql 等 MysqlClient 访问数据库。如果您无法使用客户端访问 - 您不能期望它可以与 java 一起使用。

标签: java mysql database


【解决方案1】:

您似乎没有为您的用户设置密码。 转到mysql 数据库并检查user 表以确认用户的用户名和密码。

【讨论】:

    【解决方案2】:

    这可能是使用用户名+密码组合但未在数据库端启用本机身份验证的问题。

    您是否可以使用此命令更改用户的密码:

    ALTER USER 'jeffrey'@'localhost'
    IDENTIFIED WITH mysql_native_password
    BY 'password';
    

    https://dev.mysql.com/doc/refman/8.0/en/alter-user.html

    有关本地身份验证如何工作的更多信息,请参阅

    MySQL 8.0 Reference for Native Pluggable Authentication

    或者如果您使用的是 MySQL 5.7,请参阅 MySQL 5.7 Reference for Native Pluggable Authentication

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-03
      • 1970-01-01
      • 2017-01-20
      • 1970-01-01
      • 2018-11-30
      • 2015-10-10
      • 2016-09-30
      相关资源
      最近更新 更多