Connect To MySQL With JDBC Driver

Here is an example to connect your JDBC code to MySQl database. You have to download mysql.jar for the JDBC driver class from here.

Class.forName("com.mysql.jdbc.Driver");
Connection conn = null;
conn = DriverManager.getConnection("jdbc:mysql://hostname:port/dbname","username", "password");
conn.close();

 

package javabeat.net.db;

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

public class MySQLConnectionExample {
	public static void main(String[] argv) {

		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			System.out.println("Problem in loading the MySQL Driver class!!!");
			e.printStackTrace();
			return;
		}

		Connection connection = null;

		try {
			//Get the connection object
			connection = DriverManager
			.getConnection("jdbc:mysql://<host>:3306/<dbname>","<username>", "<password>");

		} catch (SQLException e) {
			System.out.println("Problem in establishing connection!!");
			e.printStackTrace();
			return;
		}

		if (connection != null) {
			System.out.println("Connection created successfully!!");
		} else {
			System.out.println("Problem in establishing connection!!");
		}
	  }
}

If you are not copying the mysql.jar file in the classpath, you will get the following error.

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver
	at java.net.URLClassLoader$1.run(URLClassLoader.java:366)
	at java.net.URLClassLoader$1.run(URLClassLoader.java:355)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.net.URLClassLoader.findClass(URLClassLoader.java:354)
	at java.lang.ClassLoader.loadClass(ClassLoader.java:423)
	at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:308)
	at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
	at java.lang.Class.forName0(Native Method)
	at java.lang.Class.forName(Class.java:188)
	at javabeat.net.db.MySQLConnectionExample.main(MySQLConnectionExample.java:11)

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*