Java Database Connectivity (JDBC)

Java Database Connectivity (JDBC)



Introduction:

It is used to connect the Java program to the Database. Java cannot directly interact with the database. So it uses the 3rd party application to connect and make the software dynamic.

JDBC API (Application Program Interface):

It is the set of classes and interfaces under ‘java.sql’ package that is used to connect a java program to the database and allows to make the communication between them. It is important to connect the database to  the program because it helps to make the dynamic programs and make it easier to use the program as well.

Classes under JDBC API:

a) DriverManager:-
It is used to establish the connection to the database.

b) SQLException:-
It represents the error caused by the SQL Query. If specified  database table, column does not exist or if there id mistake in SQL Query.

c) ClassNotFoundException:-
It represents the exception caused if suitable database friber is not found.

This is all about classes in java. Now lets see the INTERFACES  of the JDBC API.

Interface under JDBC API:

a) Connection:-
It is used to hold the connection to the database.

b) Statement and PreparedStatement:-
Both are used to execute SQL Query. However PreparedStatement prevents SQL injection attack. PreparedStatement is mostly used due to the security purpose.

c) CallableStatement:-
It is used to execute the stored procedure.

d) ResultSet:-
It is used to hold the data from the database data into the main memory.

e) ResultSetMetaData:-
It is used to get addition information from ResultSet like, name of columns, number of columns etc.

This is all about the Classes and Interface of the JDBC API

Steps for JDBC Connectivity

a) Load the database driver:-
Class.forName(“DriverName”);

b) Create connection to the database:-
Connection connect=DriverManager.getConnection(“url”);

c) Create SQL Query and Execute it:-
String sql=”INSERT INTO …………… “;
Statement st=connect.createStatement();
st.execute(sql);

d) Close the Connection:-
Connect.close();

For example;

import java.sql.*;
// some codes
String url="jdbc:mysql://localhost:3306/java_db";
String username="root";
String pass="";

try{
   Class.forName("com.mysql.jdbc.Driver");
   Connection conn=DriverManager.getConnection(url, uname, pass);
            
  String sql="INSERT INTO tbl_name(col1,col2,...) VALUES(?,?,...)";
PreparedStatement pst=conn.prepareStatement(sql);
pst.setString(1, val1);
pst.setString(2, val2);
|
|
pst.executeUpdate();
conn.close();
}catch(Exception ex){
System.out.println(ex);

Post a Comment

0 Comments