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
3) Scroll down and click ‘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
– 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 { Class.forName(driver); 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
2) Test connection, type below :
java -cp mysql-connector-java-5.1.36-bin.jar;. TestConnection
FINISH!!