Saturday, 14 June 2014

Connect to a database in Java

Goal

In my last post I showed how to change the default password of mysql in wamp. In this post I will show how can we connect to a database(mysql is this case) using Java. You must have mysql database installed for this.

Setup

Prior to start coding lets see what we need to complete this goal. We have mysql installed.

Driver not found. Provide the driver jar in the class path.
java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Unknown Source)
at com.opensourceforgeeks.DBConnectionDemo.main(DBConnectionDemo.java:19)
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost:3306/testDB
at java.sql.DriverManager.getConnection(Unknown Source)
at java.sql.DriverManager.getConnection(Unknown Source)
at com.opensourceforgeeks.DBConnectionDemo.main(DBConnectionDemo.java:25)

This is expected as we have not added the required driver jar file yet. So add the jar to your classpath.

NOTE : If you are using java 7 like me the there is no need to even load you driver class using Class.forName() because java7 comes with JDBC 4 and for JDBC 4 appropriate driver class will automatically be picked up from the class path. So all you have to do is add the jar in the class path.