Home  >  Article  >  Java  >  How to Fix \"Access denied for user \'root\'@\'localhost\'\" Error when Connecting to MySQL with Java?

How to Fix \"Access denied for user \'root\'@\'localhost\'\" Error when Connecting to MySQL with Java?

Linda Hamilton
Linda HamiltonOriginal
2024-10-25 04:33:29763browse

How to Fix

Querying a MySQL Database with Java

When trying to establish a connection to a MySQL database using the Java code snippet below:

<code class="java">Class.forName("com.mysql.jdbc.Driver");
Connection m_connection = DriverManager.getConnection("jdbc:mysql://localhost","root","root");</code>

you may encounter the following SQLException:

<code class="java">java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)</code>

This error is typically caused by a lack of proper permissions for the root user. To resolve this issue:

  1. Grant Privileges: Use the following query in a command line tool or GUI to grant the root user on localhost all privileges on all databases:
<code class="sql">GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' IDENTIFIED BY '%password%' WITH GRANT OPTION;</code>
  1. Replace Password Placeholder: Replace %password% with the actual password for the root user.

Once the permissions are granted, you should be able to connect to the database successfully using the specified credentials.

The above is the detailed content of How to Fix \"Access denied for user \'root\'@\'localhost\'\" Error when Connecting to MySQL with Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn