问题
I have this Tetris game written in Java, which uses DB to record high scores. It worked ok as long as I was using remote MySQL DB, but now I'm trying to set up localhost DB using XAMPP MySQL and it keeps going like "SQLException: Communications link failure" at command:
con = java.sql.DriverManager.getConnection("jdbc:mysql://localhost/score", user, psw);
I guess it's either wrong URL or DB configuration, but I really don't know what to check. Any ideas?
EDIT: My friend has fixed my problem by replacing "localhost" in URL by "127.0.0.1" (which was quite embarrassing as you can surely imagine :P ).
So question is: Why is XAMPP not able to translate "localhost" into IP address and how to fix it?
回答1:
Why is XAMPP not able to translate "localhost" into IP address and how to fix it?
This is not a XAMPP problem nor a programming problem. This is more a DNS problem.
To start, do you have a %SystemRoot%/system32/drivers/etc/hosts
file with the following line as first line? (thus, after all comments, but before any other host declarations)
127.0.0.1 localhost
Update: as per the comments I've Googled a bit and it look like that the MySQL JDBC driver doesn't eat IPv6 addresses at all. In other words, you'll need to change ::1
to 127.0.0.1
. But I also found this topic which mentions that you can use the following JVM argument to fix this problem:
java -Djava.net.preferIPv4Stack=true
回答2:
I tried and got a successful connection. First create a database in phpmyadmin - eg. 'mydb' and then in code put connection.url with this value
'jdbc:mysql://localhost:3306/mydb'
If you don't create a database first it wont connect
回答3:
In MySql you have to allow access for your user from localhost explicitly. Here is an example (taken from here):
mysql> grant usage on *.* to amarokuser@localhost identified by 'amarokpasswd';
mysql> grant all privileges on amarokdb.* to amarokuser@localhost ;
来源:https://stackoverflow.com/questions/2168969/how-to-connect-xampp-mysql-local-db-using-jdbc