Wednesday, August 24, 2011

How to connect MySQL using JDBC.

I'm going to explain how to connect to MySQL server using JDBC and connector/J. I'm using Eclipse IDE. So first you must have MySQL connector/J. You can download it from http://www.mysql.com/downloads/connector/j/
After downloading extract it. You just want the mysql-*********.jar file.
So if you are using Eclipse I'll show how to add connector later. If you are not there are two ways to add connector. First method is just copy and paste the .jar in to same folder where your .class files are being. Other method is set CLASSPATH. This link will show you how to set the CLASSPATH. http://ac-support.europe.umuc.edu/~arnoldyl/NetBeansTutorials/Setting-Classpath.html
If you are using Eclipse just open the New java project. In there give appropriate name and click next. Click the tab libraries click button Add External JARs. And give the path to mysql-connector-java.jar. And click finish. Now it is OK. Now you can connect to MySQL. Here is some sample code:
import java.sql.*;
public class Main {

	public static void main(String[] args) {

		Connection conn = null;
	        ResultSet rs = null;

		try {
			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/dbname","root","password");
			Statement st = conn.createStatement();
			rs = st.executeQuery("SELECT * FROM emp");
			System.out.println(conn.getCatalog());
		} catch (ClassNotFoundException e) {
			System.out.println(e.toString());
	        } catch (SQLException ex) {
			System.out.println(ex.toString());
	        }

		try {
		     while(rs.next()){
			System.out.println(rs.getInt(1)+"\t"+rs.getString(2));
		     }
                } catch (SQLException e) {
			e.printStackTrace();
		}
	}
}
* To run this code you must have database and some tables in your MySQL sever.

0 comments:

Visitors Count

Free Hit Counter