Module_5_JDBC API-Architecture -Drivers Database Connectivity in Java
Module_5_JDBC API-Architecture -Drivers Database Connectivity in Java
4
General Architecture JDBC-to-database
Java Application
JDBC API
Driver Manager
ODBC Driver
Database
Database
Types of JDBC Architecture(2-tier and 3-tier)
• The JDBC architecture consists of two-tier and three-tier processing models to access a database.
They are as described below:
1. 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 for those queries are sent back to the user in
the form of results. The data source can be located on a different machine on a network to which a
user is connected.
• This is known as a client/server configuration, where the user’s machine acts as a client, and the
machine has the data source running acts as the server.
8
1) JDBC-ODBC bridge driver
• The JDBC-ODBC bridge driver uses ODBC driver to connect to the database.
• The JDBC-ODBC bridge driver converts JDBC method calls into the ODBC function calls.
• This is now discouraged because of thin driver.
10
3) Network Protocol driver
• The Network Protocol driver uses middleware (application server) that converts JDBC calls directly or
indirectly into the vendor-specific database protocol.
• It is fully written in java.
11
4) Thin driver
• The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is why it
is known as thin driver.
• It is fully written in Java language.
12
Interfaces and Classes of JDBC API
A list of popular interfaces of JDBC API is given below:
• Driver interface
• Connection interface
• Statement interface
• PreparedStatement interface
• CallableStatement interface
Classes of JDBC API:
• ResultSet interface
A list of popular classes of JDBC API is given below:
• ResultSetMetaData interface
•DriverManager class
• DatabaseMetaData interface
• RowSet interface •Blob class
•Clob class
•Types class
13
Database connectivity or JDBC Connection in Java
• Database connectivity or JDBC Connection means Establishing a connection between : the front end i.e
your Java Program and the back end i.e the database.
• user: Username from which your SQL command prompt can be accessed.
• password: password from which the SQL command prompt can be accessed.
• con: It is a reference to the Connection interface.
• Url: Uniform Resource Locator which is created as shown below:
String url = "jdbc:mysql://localhost:3306/university";
14
Cont..
Step 4 – Create a statement : Once a connection is established you can interact with the database. The
JDBCStatement, CallableStatement, and PreparedStatement interfaces define the methods that enable
you to send SQL commands and receive data from your database.
Use of JDBC Statement is as follows:
Statement st = con.createStatement();
Step 5 – Execute the query: Now comes the most important part i.e executing the query. The query here
is an SQL Query. Now we know we can have multiple types of queries.
Some of them are as follows:
• The query for updating/inserting a table in a database.
• The query for retrieving data.
The executeQuery() method of the 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.
The executeUpdate(sql query) method of the Statement interface is used to execute queries of
updating/inserting. 15
Cont..
• Step 6 – Close the connections
resultSet.close();
statement.close();
connection.close();
16
Understand the main JDBC interfaces and classes
• Let’s take an overview look at the JDBC’s main interfaces and classes with which we usually work. They are
all available under the java.sql package:
• DriverManager: this class is used to register driver for a specific database type (e.g. MySQL in this tutorial)
and to establish a database connection with the server via its getConnection() method.
• Connection: this interface represents an established database connection (session) from which we can create
statements to execute queries and retrieve results, get metadata about the database, close connection, etc.
• Statement and PreparedStatement: these interfaces are used to execute static SQL query and
parameterized SQL query, respectively. Statement is the super interface of the PreparedStatement interface.
Their commonly used methods are:
1. boolean execute(String sql): executes a general SQL statement. It returns true if the query returns
a ResultSet, false if the query returns an update count or returns nothing. This method can be used
with a Statement only.
2. int executeUpdate(String sql): executes an INSERT, UPDATE or DELETE statement and returns
an update account indicating number of rows affected (e.g. 1 row inserted, or 2 rows updated, or 0
rows affected).
3. ResultSet executeQuery(String sql): executes a SELECT statement and returns a ResultSet object
which contains results returned by the query 17
Cont..
• A prepared statement is one that contains placeholders (in form question marks ?) for dynamic
values will be set at runtime. For example:
• SELECT * from Users WHERE user_id=?
• Here the value of user_id is parameterized by a question mark and will be set by one of
the setXXX() methods from the PreparedStatement interface, e.g. setInt(int index, int value).
• ResultSet: contains table data returned by a SELECT query. Use this object to iterate over rows in the
result set using next() method, and get value of a column in the current row using getXXX() methods
(e.g. getString(), getInt(), getFloat() and so on). The column value can be retrieved either by index
number (1-based) or by column name.
• SQLException: this checked exception is declared to be thrown by all the above methods, so we have
to catch this exception explicitly when calling the above classes’ methods.
18
CRUD Operation with JDBC
• the steps of setting up a simple CRUD (create or insert, read, update, delete) operation using JDBC.
1. Create a new record: We can use the connection object to create a new record in the database. To
do this, we will need to use an SQL INSERT statement and execute it using the connection object.
Using PreparedStatement Interface:
try {
String sql = "INSERT INTO table_name (column1, column2, column3) VALUES (?, ?,
?)";
PreparedStatement statement = con.prepareStatement(sql);
statement.setString(1, "value1");
statement.setString(2, "value2");
statement.setInt(3, 123);
statement.executeUpdate();
System.out.println("Record created.");
} catch (SQLException e) {
e.printStackTrace();
} 19
Using Statement interface:
public static void createData(){
final String url = "jdbc:mysql://localhost:3306/employeedb";
final String uname = "root";
final String pass = "";
Scanner sc = new Scanner(System.in);
System.out.println("\t\t\t*Please Remember 'Your ID' number for further
Updatation.....");
System.out.print("\t\t\tEnter employee ID number : ");
int id = sc.nextInt();
System.out.print("\t\t\tEnter employee name : ");
String name = sc.next();
System.out.print("\t\t\tEnter employee department : ");
String department = sc.next();
System.out.print("\t\t\tEnter employee Location : ");
String location = sc.next();
String query="INSERT INTO employees (id, name, department, location) values
('"+id+"','"+name+"','"+department+"','"+location+"')";
20
try{
Connection con=DriverManager.getConnection(url,uname,pass);
Statement stmt = con.createStatement();
int rows = stmt.executeUpdate(query);
if(rows==1) {
System.out.println("\t\t\t rows affected....");
}else {
System.out.println("\t\t\tSomething is Wrong.....!! ");
}
}
}
21
2. Read a record:
To read a record from the database, you will need to use an SQL SELECT statement and execute it using
the connection object. The result of the query will be a ResultSet object that you can use to access the
data in the record.
try {
String sql = "SELECT column1, column2, column3 FROM table_name WHERE id = ?";
PreparedStatement statement = con.prepareStatement(sql);
statement.setInt(1, 1);
ResultSet result = statement.executeQuery();
if (result.next()) {
String column1 = result.getString("column1");
String column2 = result.getString("column2");
int column3 = result.getInt("column3");
System.out.println("Column 1: " + column1);
System.out.println("Column 2: " + column2);
System.out.println("Column 3: " + column3);
}
} catch (SQLException e) {
e.printStackTrace();
}
22
3. Update a record:
To update a record in the database, you will need to use an SQL UPDATE statement and execute it using
the connection object.
try {
String sql = "UPDATE table_name SET column1 = ?, column2 = ?, column3 = ?
WHERE id = ?";
PreparedStatement statement = con.prepareStatement(sql);
statement.setString(1, "new_value1");
statement.setString(2, "new_value2");
statement.setInt(3, 456);
statement.setInt(4, 1);
statement.executeUpdate();
System.out.println("Record updated.");
} catch (SQLException e) {
e.printStackTrace();
} 23
4. Delete a record:
To delete a record from the database, you will need to use an SQL DELETE statement and execute it
using the connection object.
try {
String sql = "DELETE FROM table_name WHERE id = ?";
PreparedStatement statement = con.prepareStatement(sql);
statement.setInt(1, 1);
statement.executeUpdate();
System.out.println("Record deleted.");
} catch (SQLException e) {
e.printStackTrace();
}
24
T
• has
25
T
• has
26
T
• has
27
T
• has
28