Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to connect XAMPP MySQL local DB using JDBC?

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?

like image 973
Jakub Stejskal Avatar asked Jan 30 '10 18:01

Jakub Stejskal


People also ask

How does JDBC connect to MySQL?

Connection URL: The connection URL for the mysql database is jdbc:mysql://localhost:3306/sonoo where jdbc is the API, mysql is the database, localhost is the server name on which mysql is running, we may also use IP address, 3306 is the port number and sonoo is the database name.

Does JDBC work with MySQL?

In Java, we can connect to our database(MySQL) with JDBC(Java Database Connectivity) through the Java code. JDBC is one of the standard APIs for database connectivity, using it we can easily run our query, statement, and also fetch data from the database.

Which JDBC driver is used for MySQL?

Driver in MySQL Connector/J is com. mysql. cj. jdbc.

Where is JDBC URL MySQL?

MySQL JDBC driver To connect to MySQL from Java, you have to use the JDBC driver from MySQL. The MySQL JDBC driver is called MySQL Connector/J. You find the latest MySQL JDBC driver under the following URL: http://dev.mysql.com/downloads/connector/j.


2 Answers

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 
like image 175
BalusC Avatar answered Oct 11 '22 22:10

BalusC


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

like image 27
bhv Avatar answered Oct 11 '22 22:10

bhv