简体   繁体   中英

Access denied when trying to connect to mysql database via eclipse, java

I'm trying to connect to mysql database, but I get one and the same error: javax.servlet.ServletException: java.sql.SQLException: Access denied for user 'user'@'localhost' (using password: YES)

I've already tried the following solutions:

  1. Checked my username and password. MySQL connection is established via username = user1, password = 123. I use the same in my code, when I connect to the database: Class.forName("com.mysql.jdbc.Driver").newInstance(); Connection con = DriverManager.getConnection( "jdbc:mysql://localhost:3306/employee","user1", "123"); Class.forName("com.mysql.jdbc.Driver").newInstance(); Connection con = DriverManager.getConnection( "jdbc:mysql://localhost:3306/employee","user1", "123");
  2. Granted privileges to user1 in the following manner: GRANT ALL PRIVILEGES ON * . * TO 'user1'@'localhost'; FLUSH PRIVILEGES; GRANT ALL PRIVILEGES ON * . * TO 'user1'@'localhost'; FLUSH PRIVILEGES; By the way I have the same problem when I try to connect with 'root'@'localhost'. Do you have any ideas why it doesn't work still?

MySQL JDBC is only able to connect via TCP/IP (on Unix, or TCP/IP or named pipe on Windows).

The MySQL JDBC driver cannot establish a connection using the local unix socket.

With MySQL on Unix, localhost has a different meaning that we might expect. It is not a hostname synonym for the 127.0.0.1 TCP/IP loopback address. On Unix, MySQL user

'user1'@'localhost'

specifies a user that can connect only via unix socket file; it's not possible to connect to that user via TCP/IP.


The above explains why MySQL is refusing a connection from JDBC: the connection attempt fails because a matching user does not exist.

To create a MySQL user that connect from TCP/IP loopback address, assuming that MySQL is started with --skip-name-resolve and without --skip-networking , we can specify user as:

'user'@'127.0.0.1'

That user would allow connection from JDBC.

(If MySQL DNS name resolution is enabled, then we would need to use a hostname that resolves to the loopback address; or we can consider using a wildcard '%' for the hostname portion of the user.)

Try this out might help:

1) goto mysql terminal. 2) mysql> use mysql; 3) mysql> select user, host from user; 4) There next to you user set the host as "%" instead of localhost

.

now in the connection instead of localhost tryp specifying the ip address of the server.

Hope this helps you. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM