Test connection java to mysql

Test connection java to mysql
In this tutorial i will show you How To Test Connection Java To Mysql using JDBC (Java Database Connectivity).

– Download JDBC

1) First we need JDBC, download here
2) Choose *.tar file
download mysql connector jar
3) Scroll down and click ‘No thanks, just start my download’.
mysql - no thanks just start my download
4) Create folder java (c:/java) and extract .tar, copy mysql-connector-java-5.1.36-bin.jar to c:/java
mysql connector

– Create Java File

1) Create file TestConnection.java inside c:/java and copy the following script :

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;

public class TestConnection {

  public static void main(String[] argv) throws ClassNotFoundException {
		Connection conn = null;
		String driver 	= "com.mysql.jdbc.Driver";
		String db 		= "test";
		String url 		= "jdbc:mysql://localhost/" + db;
		String user 	= "root";
		String pass 	= "abcd.123";
        try {
            conn = DriverManager.getConnection(url,user,pass);
            System.out.println("Connected to database : " + db);
        } catch (SQLException e) {
            System.out.println("SQLException: "+e.getMessage());
            System.out.println("SQLState: "+e.getSQLState());
            System.out.println("VendorError: "+e.getErrorCode());

– Line 11 : Your db
– Line 12 : It’s jdbc connection, if you have specific port (example 8080) then you must write “jdbc:mysql://localhost:8080” + db;
– Line 13 – 14 : Your localhost user

– Test Connection

1) First, compile TestConnection.java like this :

javac -cp mysql-connector-java-5.1.36-bin.jar;. Testconnection.java

compile java
2) Test connection, type below :

java -cp mysql-connector-java-5.1.36-bin.jar;. TestConnection

successful connect to mysql with java JDBC


[related_post themes="text" id="2124"]

Ambar Hasbiyatmoko

Hello, I’m web developer. Passionate about programming, networking and web server. @kaskus  @facebook

One Comment

  1. if you want to run it in linux you need to type:
    javac -cp “mysql-connector-java-5.1.36-bin.jar:.” Testconnection.java

Leave a Reply

Your email address will not be published. Required fields are marked *

Time limit is exhausted. Please reload CAPTCHA.