info@tutsfinder.in



Java Database Connectivity

Java JDBC is an API that enables java applications to connect with relational databases like MySql.

It can access data of relational database where you update, detete , fetch , store the data from database.


JDBC Drivers


1. JDBC-ODBC Bridge Driver -JDBC drivers coverts the interface calls to ODBC calls, then ODBC bridge calls ODBC driver of the respective database. But this driver have some problems to overcome this thin driver is introduce.

2. Native API Driver - Native API Driver part is replaced by ODBC part, thi driver converts the jdbc method calls into native method calls

3. Network Protocol Driver(Middleware Driver) - In this, first java method calls send to middleware. With the help of middleware then connects to the database on behalf of JDBC Driver.

4. Database Protocol Driver(Pure java driver) or thin driver - Thin driver is most used driver. It directly coverts the JDBC methods calls to the database.


Steps to set-up JDBC Connection


1. Import JDBC packages

2. Load JDBC drivers

3. Open a connection to the database

4. Create statement

5. Execute Query

6. Get resultSet and process it

7. Close connection



Program to create a new file

In this program, we are creating a new file, If same name of file is already exist then it will give us error otherwise it will successfully created.



import java.sql.*;

public class JDBCExample {
     
   public static void main(String[] args) {
	Statement stmt=null;
	Connection con=null;
 
   try{
      
      Class.forName("com.mysql.jdbc.Driver");

      
      System.out.println("Connecting to database...");
      con = DriverManager.getConnection("jdbc:mysql://localhost:3306/project","root","root");

      
      System.out.println("Creating statement...");
      stmt = con.createStatement();
  
      ResultSet rs = stmt.executeQuery("select * from manufacturer");

      
      while(rs.next()){
         
         int id  = rs.getInt("ManufacturerID");
         String name = rs.getString("ManufacturerName");
         String address = rs.getString("Address");
         String city = rs.getString("City");
	String mobile = rs.getString("Mobile");

         
         System.out.print("ID: " + id);
         System.out.print(", Name: " + name);
         System.out.print(", Address: " + address);
         System.out.println(", City: " + city);
	System.out.println(", Mobile: " + mobile);
      }
      
      rs.close();
      stmt.close();
      con.close();
   }catch(SQLException se){
      
      System.out.println("se");
   }
   
}
}


Output:

ID: 6123, Name: abcde, Address: Lohgaon-47, City: Pune, Mobile: 123456789