JDBC : Connecting JAVA to MySQL Database


1. Database Preparation
Create schema :  create schema djSchema
Create Table     :  create table djSchema.t_dj_contacts (id int, firstname varchar(30), lastname varchar(20));
Insert Test Data:  insert into t_ dj_contacts values(1,"deepak", "jain");

2. Download and Add mysql-connector-java-5.0.8-bin.jar in classpath. This jar contains JDBC driver for MySQL.

3. Keep MySQL Database details ready 
    DB IP        :
    PortName  : In C:\Program Files (x86)\MySQL\MySQL Server 5.0\my.ini file contains the client port
    UserName :
    Password  :

4. Class is JDBCConnector.java
import java.sql.*;
public class JDBCConnector {
public void connect(){
Connection connection=null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
// load the driver
Class.forName("com.mysql.jdbc.Driver");
// create the connection
connection = DriverManager.getConnection("jdbc:mysql://localhost:9999/djSchema", "username","password");
//create statement
preparedStatement = connection.prepareStatement("select * from t_ dj_contacts");
//execute statement
resultSet = preparedStatement.executeQuery();
//process result
if(resultSet !=null && resultSet.next()){
System.out.println(resultSet.getInt("id"));
System.out.println(resultSet.getString("firstname"));
}
} //Handle Exceptions
catch (ClassNotFoundException e) {
System.out.println("Exception in initializing Database Driver");
}catch (SQLException sqe){
System.out.println("SQLException : "+sqe);
}finally{
//Close Resultset
if(resultSet !=null){
try {
resultSet.close();
} catch (SQLException e) {
System.out.println("Excpetion in Closing ResultSet"+e);
}
}
//Close Prepared Statement
if(preparedStatement != null){
try{
preparedStatement.close();
} catch (SQLException e) {
System.out.println("Excpetion in Closing Statement"+e);
}
}
//Close Connection
if(connection != null){
try{
connection.close();
} catch (SQLException e) {
System.out.println("Excpetion in Closing connection"+e);
}
}
}
}

}

5. Test the Connection
public class JDBCTest {
public static void main(String[] args) {
JDBCConnector dbconnector = new JDBCConnector();
dbconnector.connect();
}
}

Comments

Popular posts from this blog

Ashtavinayak Temples | 8 Ganpati Temples of Maharashtra | Details Travel Reviews

Ramoji Film City, Hyderabad, India

Pune to Ganpatipule Trip