About The Author

This is a sample info about the author. Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Quisque sed felis.

Get The Latest News

Sign up to receive latest news

Friday 26 August 2011

How to connect MySQL with Java?

Steps to Connnect the MySQL with JDBC:
------------------------------------------
1). Download MySQL database.
2). Install it.
3). Download the mysql-connector-java-5.1.10, it depends on your JDBC version
4). It is a type 4 driver.
5). Extract the mysql-connector-java-5.1.10 and copy the "mysql-connector-java-[version]-bin-g.jar" into such location where you can find it easily.
6). Now set the "CLASSPATH" for that jar file.
7). Copy the code and paste it to your file:

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

public class MySQLCon {

public static void main(String args[]) {
Connection con = null;

try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection("jdbc:mysql:///DATABASE NAME","root", "");

if(!con.isClosed())
System.out.println("Successfully connected to MySQL server using TCP/IP...");

} catch(Exception e) {
System.err.println("Exception: " + e.getMessage());
} finally {
try {
if(con != null)
con.close();
} catch(SQLException e) {}
}
}
}

8). Provide the Database Name and the credentials of the MySQL.
9). Compile it and run it.

0 comments:

Post a Comment