jdbc与mysql的连接错误解决——“Connect failed: Access denied for user 'root'@'localhost' (using password: YES)”

时间:2021-02-02 19:16:03


今天在用jdbc 连接MySQL数据库时一直不停的在 Statement stmt = con.createStatement() ; 这一句上报空指针异常无法连接到数据库。


然后第一步用了http://outofmemory.cn/code-snippet/1085/java-usage-JDBC-connection-MYSQL-database这个网址上的一个方法,下载:mysql-connector-java-5.1.17-bin.jar JAR包,然后放进jdk1.6.0_37\jre\lib\ext 重启eclispe 就可以在JRE系统库中看到。不过没有将问题解决。


第二步参考了*上的一个解决方案,将问题解决掉了,就是重新在MySQL数据库新建一个用户,然后将在该用户名下重建了数据库。最后在代码中将连接的用户名及密码,用新建用户。而不去使用root用户。具体内容参见:

“Connect failed: Access denied for user 'root'@'localhost' (using password: YES)” from php function

jdbc与mysql的连接错误解决——“Connect failed: Access denied for user 'root'@'localhost' (using password: YES)”jdbc与mysql的连接错误解决——“Connect failed: Access denied for user 'root'@'localhost' (using password: YES)”
up vote12down votefavorite7

I wrote some function used by a php webpage, in order to interact with a mysql database. When I test them on my server I get this error:

"Connect failed: Access denied for user 'root'@'localhost' (using password: YES)" 

I am able to use them on my pc (using XAMPP) and I can navigate through the tables of the database using the command line in the server. Instead, the webpage fails to connect. I've checked the password but with no results, it's correct (otherwise I could not log in to mysql from the command line).

The call of the function is the following:

$conn = new mysqli("localhost", "root", "password", "shop");

Have I to set something in my server? Thanks

Edit: PHP version 5.3.3-7+squeeze1 mysql version: 5.1.49-3 both on debian

share|improve this question

migrated from superuser.com Jun 22 '11 at 20:11

This question came from our site for computer enthusiasts and power users.

 
1  
What version of PHP are you running? What version of MySQL? It sounds similar tobitshop.com/Blogs/tabid/95/EntryId/67/… –  Jack Murdoch Jun 22 '11 at 20:16
add a comment | 

8 Answers 8

activeoldestvotes
up vote25down voteaccepted

I solved in this way: I logged in with root username

mysql -u root -p -h localhost

I created a new user with

CREATE USER 'francesco'@'localhost' IDENTIFIED BY 'some_pass';

then I created the database

CREATE DATABASE shop;

I granted privileges for new user for this database

GRANT ALL PRIVILEGES ON shop.* TO 'francesco'@'localhost';

Then I logged out root and logged in new user

quit;
mysql -u francesco -p -h localhost

I rebuilt my database using a script

source shop.sql;

And that's it.. Now from php works without problems with the call

 $conn = new mysqli("localhost", "francesco", "some_pass", "shop");

Thanks to all for your time :)

share|improve this answer