0% found this document useful (0 votes)
1 views30 pages

JDBC

JDBC (Java Database Connectivity) is a Java API that allows Java applications to connect and interact with various databases through a standard abstraction. It consists of components such as the JDBC API, Driver Manager, and different types of JDBC drivers (Type-1 to Type-4) that facilitate communication between Java applications and databases. The document also covers JDBC interfaces, execution methods, and batch processing for efficient database operations.

Uploaded by

vishal9035901911
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views30 pages

JDBC

JDBC (Java Database Connectivity) is a Java API that allows Java applications to connect and interact with various databases through a standard abstraction. It consists of components such as the JDBC API, Driver Manager, and different types of JDBC drivers (Type-1 to Type-4) that facilitate communication between Java applications and databases. The document also covers JDBC interfaces, execution methods, and batch processing for efficient database operations.

Uploaded by

vishal9035901911
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 30

JDBC or Java Database Connectivity is a Java API to connect and

execute the query with the database.

It is a specification from Sun microsystems that provides a standard


abstraction(API or Protocol) for java applications to communicate with
various databases.

JDBC, along with the database driver, can access databases and
spreadsheets.

Definition of JDBC(Java Database Connectivity)


JDBC is an API(Application programming interface) used in java
programming to interact with databases. The classes and interfaces of
JDBC allow the application to send requests made by users to the
specified database.
Components of JDBC

1. JDBC API: It provides various methods and interfaces for easy communication
with the database. It provides two packages as follows, which contain the java SE
and Java EE platforms to exhibit WORA(write once run anywhere) capabilities.
1. java.sql.* 2. javax.sql.*

2. JDBC Driver manager: It loads a database-specific driver in an application to


establish a connection with a database. It is used to make a database-specific call
to the database to process the user request.

3. JDBC Test suite: It is used to test the operation(such as insertion, deletion,


updation) being performed by JDBC Drivers.

4. JDBC-ODBC Bridge Drivers: It connects database drivers to the database. This


bridge translates the JDBC method call to the ODBC function call. It makes use of
the sun.jdbc.odbc package which includes a native library to access ODBC
characteristics.
JDBC Drivers
JDBC drivers are client-side adapters (installed on the client machine, not on the server) that
convert requests from Java programs to a protocol that the DBMS can understand.

There are 4 types of JDBC drivers:


1. Type-1 driver or JDBC-ODBC bridge driver
2. Type-2 driver or Native-API driver
3. Type-3 driver or Network Protocol driver
4. Type-4 driver or Thin driver

Types of JDBC Architecture(2-tier and 3-tier)

Two-tier model: A java application communicates directly to the data source.


- The JDBC driver enables the communication between the application and the data source. -
When a user sends a query to the data source, the answers are sent back to the user.
- This is known as a client/server configuration.

Three-tier model: the user’s queries are sent to middle-tier services, from which the
commands are again sent to the data source. The results are sent back to the middle tier,
and from there to the user.
This type of model is found very useful by management information system directors.
Type-1 Driver: JDBCD-ODBC Bridge Driver
 Acts as bridge between JDBC and other database connectivity mechanism like ODBC.
 Example: Sun JDBC-ODBC bridge driver(in sun.jdbc.odbc package)
 Converts JDBC calls into ODBC calls and redirects the request to ODBC driver
 ODBC driver uses SP(Stored Procedure) APIs to make DBMS specific call
Advantages
 Single driver implementation for different databases
 Vendor independent driver
 Supports all databases supported by the ODBC driver
Disadvantages
 Slow execution speed due to large number of calls and translations
 Fully dependent on ODBC driver
 ODBC client library should be installed at client machine
Type-2 Driver: Java to Native API(Partly Java Driver)
 Type-2 Driver converts JDBC calls into database vendor specific native call using JNI
 These database specific calls then dispatched to db specific native libraries
 Native libraries sends request to db server by native protocol
 Example: Weblogic Type-2 Driver by BEA Weblogic
Advantages
 Fast processing as compared to Type-1 Driver
 Contains exclusive feature provided by DB vendor and supported by JDBC specification
Disadvantages
 Native librariesto be installed on client machine
 Executes DB specific native functions on JVM, bug in Type-2 driver might crash JVM
 Increase the cost of application in case it runs on different platforms
Type-3 Driver: Java to Network Protocol(Pure Java Driver)
 Type-3 Driver converts JDBC calls into middleware server specific calls
 Driver communicates with middleware over a socket
 Middleware converts these calls into database specific calls
 These type of drivers also known as net-protocol drivers
 Example: IDS Driver, WebLogic RMI Driver
Advantages
 Additional features like Pool Management, performance improvement and connection availability and auto
downloadable
 No native library needed to be installed in client machine
 Database independent, middleware takes care of converting calls to DB specific calls
 Database details are not required at client side because it is available at middleware server
 Easy to switch among databases, without changing client side driver classes
Disadvantages
 Performes task slowly because network call is involved
 Cost of middleware server is more
Type-4 Driver: Java to Database Protocol(Pure Java Driver)
• Implements the database protocol to interact directly with a database
• prepares a DBMS specific network message & communicates with DB server -socket
• Type-4 Driver uses DB specific proprietary protocol for communication
• Generally,are implemented by DBMS vendors, since the protocols used are proprietary
• Example: Oracle Thin driver, WebLogic & Mysqlserver4 for MY SQL server
Advantages
 This is lightweight driver
 Auto downloadable
 No native library needed to be installed at client side
 No middleware server required
Disadvantages
 This uses database specific proprietary protocol so it is vendor dependent
Essentials of JDBC Program
import java.sql.*; // Import Package

public class JDBCDemo {


public static void main(String args[]) throws SQLException, ClassNotFoundException {
String driverClassName = "com.mysql.jdbc.Driver";
String url = "jdbc:odbc:XE";
String username = "scott";
String password = "tiger";
String query = "insert into students values(109, 'bhatt')";

Class.forName(driverClassName); // Load driver class

Connection con = DriverManager.getConnection(url, username, password);


// Obtain a connection
Statement st = con.createStatement(); // Obtain a statement

int count = st.executeUpdate(query); // Execute the query

System.out.println( "number of rows affected by this query= "+ count);

con.close(); // Close the connection


}
}
MySQL com.mysql.jdbc.Driver

ORACLE oracle.jdbc.driver.OracleDriver

DB2 COM.ibm.db2.jdbc.net.DB2Driver

Sybase com.sybase.jdbc.SybDriver
Interfaces of JDBC API
• Driver interface
• Connection interface
• Statement interface
• PreparedStatement interface
• CallableStatement interface
• ResultSet interface
• ResultSetMetaData interface
• DatabaseMetaData interface
• RowSet interface
• Classes of JDBC API

Classes of JDBC API


• DriverManager class
• Blob class
• Clob class
• Types class
The JDBC Interfaces
• Statement,
• CallableStatement, and
• PreparedStatement
interfaces define the methods and properties that enable you to send
SQL or PL/SQL commands and receive data from your database.

Interfaces Recommended Use

Statement • Use this for general-purpose access to your database.


• Useful when you are using static SQL statements at runtime.
• The Statement interface cannot accept parameters.

PreparedStatement • Use this when you plan to use the SQL statements many times.
• The PreparedStatement interface accepts input parameters at
runtime.

CallableStatement • Use this when you want to access the database stored procedures.
• The CallableStatement interface can also accept runtime input
parameters.
Statement Interface
• Represents object that is used for executing a static SQL statement and returning the
results it produces.

• Connection.createStement() creates a Statement object for sending SQL statements to


the database.

• SQL Statements without parameters are normally executed using Statement Objects.

• In case if same SQL statement is executed many times, it may be more efficient to use
PreparedStatement object.

• Statement.execute, Statement.executeUpdate and Statement.executeQuery methods


used to execute static SQL statement.

• ResultSet object is returned as result which static SQL statement produces while
execution.

• By default, only one ResultSet object per Statement object can be open at the same
time.

• All execution methods in the Statement interface implicitly close a current ResultSet
object of the statement if an open one exists.
import java.sql.*;
public class JDBCExample {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; // JDBC driver name
and database URL
static final String DB_URL = "jdbc:mysql://localhost/STUDENTS";
static final String USER = "username"; // Database
credentials
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
Class.forName("com.mysql.jdbc.Driver"); //STEP 2: Register JDBC driver
System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS); //STEP 3: Open a
connection
System.out.println("Connected database successfully...");
System.out.println("Inserting records into the table...");
stmt = conn.createStatement(); //STEP 4: Create statement and
Execute query
String sql = "INSERT INTO Registration " + "VALUES (100, 'Zara', 'Ali', 18)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Registration " + "VALUES (101, 'Mahnaz', 'Fatma', 25)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Registration " + "VALUES (102, 'Zaid', 'Khan', 30)";
stmt.executeUpdate(sql);
sql = "INSERT INTO Registration " + "VALUES(103, 'Sumit', 'Mittal', 28)";
stmt.executeUpdate(sql);
System.out.println("Inserted records into the table...");
} //end main
} //end JDBCExample
Execution control of statement
PreparedStatement Interface
• An object that represents precompiled SQL statement

• This object can then be used to efficiently execute this statement multiple times

• The setter methods (setShort, setString, and so on) for setting IN parameter values must
specify types that are compatible with the defined SQL type of the input parameter.

• For instance, if the IN parameter has SQL type INTEGER, then the method setInt should
be used.

• An object that represents precompiled SQL statement.

String sql = "insert into emp values(?,?,?,?)";


import java.sql.*;
import java.io.*;
public class PreparedStatementExInsert{
public static void main(String[] args)throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","system","manager");
String sql = "insert into emp values(?,?,?,?)";
PreparedStatement ps = con.prepareStatement(sql);
DataInputStream dis = new DataInputStream(System.in);
do{
System.out.print("EmpNo: ");
int eno = Integer.parseInt(dis.readLine());
System.out.print("EmpName: ");
String ename = dis.readLine();
System.out.print("Salary: ");
double sal = Double.parseDouble(dis.readLine());
System.out.print("Dept: ");
int dno = Integer.parseInt(dis.readLine());

ps.setInt(1,eno);
ps.setString(2,ename);
ps.setDouble(3,sal);
ps.setInt(4,dno);

ps.executeUpdate();
System.out.println("Want to add more? ");
}while(dis.readLine().equalsIgnoreCase("y"));
con.close();
}
}
ResultSet interface

Represents table of data, usually generated by executing a statement that queries database.

• A ResultSet object maintains a cursor to its current row of data

• Initially cursor points before the first row

• ResultSet.next method moves the cursor to next row of data

• ResultSet.next method returns false if there is no more rows in ResultSet object

• ResultSet cursor moves forward only

• To iterate through ResultSet object while loop can be used

• ResultSet interface provides getter methods(like getString, getInt, and so on) to retrieve
column value from the current row

• Values can be retrieved using either the index number of the column or the name of the
column
• In general using column number will be more efficient, it starts from 1 not 0

• ResultSet columns within each row should be read in left-to-right order


Example for Resultset object using statement interface
import java.sql.*;
public class JDBCExample {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/STUDENTS";
static final String USER = "username";
static final String PASS = "password";
public static void main(String[] args) {

Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to a selected
database...");
Connection conn = DriverManager.getConnection(DB_URL, USER,
PASS);
System.out.println("Connected database successfully...");

System.out.println("Creating statement...");
Statement stmt = conn.createStatement();
String sql = "SELECT id, first, last, age FROM
Registration";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last); }
rs.close();
} }
Example for Resultset object using prepared statement
import java.sql.*;
import java.io.*;
public class PreparedStatementExSelect{
public static void main(String[] args)throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","system","manager");
String sql = "SELECT * FROM emp WHERE empno=?";
PreparedStatement ps = con.prepareStatement(sql);
DataInputStream dis = new DataInputStream(System.in);
do{
System.out.print("EmpNo: ");
int eno = Integer.parseInt(dis.readLine());
ps.setInt(1,eno);
ResultSet rs = ps.executeQuery();
if(rs.next()) {
System.out.println(rs.getInt(1)+"\t"+rs.getString(2)+"\t"+rs.getDouble(3)+"\t"+rs.getInt(4));
}
else{
System.out.println("Employee Not Found!");
}
System.out.println("Want to find one more? ");
}while(dis.readLine().equalsIgnoreCase("y"));
con.close();
} }
Execute the query

Query here is an SQL Query .


• Query for updating / inserting table in a database.
• Query for retrieving data .

Once you've created a Statement object, you can then use it to execute an SQL statement
with one of its three execute methods.

1. boolean execute (String SQL): Returns a boolean value of true if a ResultSet


object can be retrieved; otherwise, it returns false. Use this method to execute SQL
DDL statements or when you need to use truly dynamic SQL.

2. int executeUpdate (String SQL): Returns the number of rows affected by the
execution of the SQL statement. Use this method to execute SQL statements for
which you expect to get a number of rows affected - for example, an INSERT,
UPDATE, or DELETE statement.

3. executeQuery() method of Statement interface is used to execute queries of


retrieving values from the database. This method returns the object of ResultSet
that can be used to get all the records of a table.
Compare Statement and PreparedStatement

Statement PreparedStatement
1. Single object can execute multiple 1. Only one SQL
SQL
2. Every execution of SQL needs 2. Only one compilation for multiple
compilation execution of SQL
3. Difficult to include multiple 3. Easy writing SQL because of
concatanation positional parameters
4. Needs DB specific format 4. Easy working with compiler types

5. SQL injection attacks possibility is 5. Limited SQL injection attacks


more
Batch Processing
Batch Processing allows you to group related SQL statements into a batch and
submit them with one call to the database.

The addBatch() method of Statement,


PreparedStatement and CallableStatement is used to add individual statements to
the batch.

The executeBatch() is used to start the execution of all the statements grouped
together.

The executeBatch() returns an array of integers, and each element of the array
represents the update count for the respective update statement.

Just as you can add statements to a batch for processing, you can remove them
with the clearBatch() method.
This method removes all the statements you added with the addBatch() method.
However, you cannot selectively choose which statement to remove.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy