As you all know Java is one of the best programming languages around and MySQL is the world’s most popular open source database. Often these are used to build business applications. There arises the need to connect both of these technologies. But for a newbie like me it is quite a daunting task to make them talk to each other. So, I am putting forward a tutorial showing how to accomplish the task.
I am assuming that the reader have installed both Java and MySQL.
First of all we need MySQL Connector/J driver. It is the official JDBC driver for MySQL. Which can be downloaded from http://dev.mysql.com/downloads/connector/j/ .Moreover I have enclosed the driver used for this tutorial.
It was the easy part. Now the most confusing part if you don’t know how to set classpath. Classpath can be set in more than one way. I shall use the method which I prefer the most.
The file name of the MySQL Connector/J driver I have downloaded is
mysql-connector-java-5.1.11-bin.jar
I have kept this file in C:\Program Files\Java\jdk1.6.0_12\lib in my system. You can place it anywhere you like.
JAR file (or Java ARchive) collection of many files into one. Java developers generally use .jar files to distribute Java applications or libraries, in the form of classes and associated metadata and resources. In this case mysql-connector-java-5.1.11-bin.jar file contains all the classes required for Java, MySQL connection.
Now I shall set the classpath so that our program can use this library to connect the MySQL database.
Click Start or the Windows icon in the bottom left corner of your screen. Then Select Computer, Properties.
Now Select Advanced System Settings
Select Environment Variable in the System Properties Window
Choose ClassPath from the System Variable Pane and click Edit Button.
Enter the Path of mysql-connector-java-5.1.11-bin.jar file after putting a semicolon in case there are previous settings. In most cases there you would find some. Click Ok couples of time. That’s all. You have set the classpath. In some instances you might have to restart your system.
Now we shall write the code to connect MySQL database.
import java.sql.*;
public class TestConnection{
public static void main(String[] args) {
System.out.println("MySQL Connect Example.");
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "test";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "";
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,password);
System.out.println("Connected to the database");
conn.close();
System.out.println("Disconnected from database");
} catch (Exception e) {
e.printStackTrace();
}
}
}
mysql-connector-java-5.1.11-bin.jar is the best as i am connnected with it with the latest version am facing some issues will post after correcting them......
Thank you guys............Stay tuned !!!!!!!!