0% found this document useful (0 votes)
3 views

Chapter 3

The document provides an overview of JDBC (Java Database Connectivity), detailing its architecture, types of JDBC drivers, and the steps to connect a Java application to a database. It explains the advantages and disadvantages of different JDBC driver types, including JDBC-ODBC bridge, Native-API, Network Protocol, and Thin drivers. Additionally, it outlines how to execute SQL queries and retrieve metadata using JDBC interfaces such as ResultSetMetaData and DatabaseMetaData.

Uploaded by

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

Chapter 3

The document provides an overview of JDBC (Java Database Connectivity), detailing its architecture, types of JDBC drivers, and the steps to connect a Java application to a database. It explains the advantages and disadvantages of different JDBC driver types, including JDBC-ODBC bridge, Native-API, Network Protocol, and Thin drivers. Additionally, it outlines how to execute SQL queries and retrieve metadata using JDBC interfaces such as ResultSetMetaData and DatabaseMetaData.

Uploaded by

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

1

2
• Programs connect to, and interact with, relational databases a
software that facilitates communications between a database
management system and a program.

• A JDBC driver enables Java applications to connect to a database in


a particular DBMS and allows you to retrieve and manipulate
database data.

• Package java.sql contains classes and interfaces for accessing


relational databases in Java.

• Using the JDBC API enables developers to change the underlying


DBMS without modifying the Java code that accesses the database.
3
Fig 4.1: JDBC

4
• JDBC architecture is composed of two key layers:

• JDBC API: Serves as the intermediary between the Java


application and the JDBC manager. It provides a set of interfaces
and classes for Java applications to interact with the JDBC
manager.

• JDBC driver: Acts as the bridge between the JDBC manager and
the specific database driver. JDBC drivers are database-specific
and are responsible for translating JDBC calls into commands that
the respective database understands.
5
o JDBC Driver is a software component that enables java application to

interact with the database. There are 4 types of JDBC drivers:

1. JDBC-ODBC bridge driver

2. Native-API driver (partially java driver)

3. Network Protocol driver (fully java driver)

4. Thin driver (fully java driver)

6
1) JDBC-ODBC bridge driver(Type 1)

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.

7
1) JDBC-ODBC

Advantages:
•easy to use.
•can be connected to any database.

Disadvantages:
•Performance degraded because JDBC method call is converted
into the ODBC function calls.
•The ODBC driver needs to be installed on the client machine.
•This type of driver cannot talk to the database directly.
8
2) Native-API driver (Type 2)
The Native API driver uses the client-side libraries of the database. The driver
converts JDBC method calls into native calls of the database API. It is not

written entirely in java.

9
2) Native-API driver

Advantage:

•performance upgraded than JDBC-ODBC bridge driver.

Disadvantage:

•The Native driver needs to be installed on the each client


machine.

•The Vendor client library needs to be installed on client


machine.

10
3) Network Protocol driver (Type 3)

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
Network Protocol driver

Advantage:

•No client side library is required because of application server that can
perform many tasks like auditing, load balancing, logging etc.

Disadvantages:

•Network support is required on client machine.

•Requires database-specific coding to be done in the middle tier.

•Maintenance of Network Protocol driver becomes costly because it requires


database-specific coding to be done in the middle tier.

12
4) Thin driver –Pure Java (Type 4)
oThe 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.

13
4) Thin driver
Advantage:

•Better performance than all other drivers.

•Does not require any native library.

Disadvantage:

•Drivers depends on the Database.

14
• The JDBC architecture is sometimes classified as: two-tier and three-tier.
Type 2 and 4 drivers use two-tier and Type 1 and 3 use three-tier
architecture.

• Figure 4.2. (i) and (ii) show the JDBC two-tier and three-tier
architectures.

15
• Java provides an API for accessing and processing data stored in a data
source (usually a relational database).
Table 1: Java JDBC classes and interfaces

16
Steps to connect to the database in java

There are 5 steps to connect any java application with the


database in java using JDBC. They are as follows:

1.Register the driver class

2.Creating connection

3.Creating statement

4.Executing queries

5.Closing connection
17
Steps to connect to the database in java

1) Register the driver class


oThe forName() method of Class class is used to register the driver class. This

method is used to dynamically load the driver class.

Syntax of forName() method


public static void forName(String className)throws ClassNotFoundException

Example to register the Mysql /Oracle Driver class

Class.forName("com.mysql.jdbc.Driver");

Class.forName("oracle.jdbc.driver.OracleDriver");

18
2) Create the connection object
oThe getConnection() method of DriverManager class is used to establish
connection with the database.
Syntax of getConnection() method

Example to establish connection with the MySQL database

Connection con=DriverManager.getConnection("jdbc:mysql://hostname:port/dbName",“un",“PW");

//here dbName is database name, un is username and PW is password

19
Example to connect to the database in java:
public class JDBCDemo {
public static void main(String[] args) {
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase",
"username", "password");
if (connection != null) {
System.out.println("Connected to the database!");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
} } }}
20
3) Create the Statement object
oThe createStatement() method of Connection interface is used to create
statement. The object of statement is responsible to execute queries with the
database.

oSyntax of createStatement() method

public Statement createStatement()throws SQLException

Example: Statement stmt=con.createStatement();

21
4) Execute the query
oThe executeQuery() method of Statement interface is used to execute queries
to the database. This method returns the object of ResultSet that can be used to
get all the records of a table.

Syntax of executeQuery() method

public ResultSet executeQuery(String sql) throws SQLException

Example to execute query

ResultSet rs=stmt.executeQuery("select * from stud");

while(rs.next()){

System.out.println(rs.getInt(1)+" "+rs.getString(2)); }
22
SQL (Structured Query Language)
import java.sql.*;

public class JDBCDemo {


public static void main(String[] args) {
Connection connection = null;
Statement statement = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase",
"username", "password");
statement = connection.createStatement();
String sql = "SELECT * FROM customers";
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
String name = resultSet.getString("name");
int age = resultSet.getInt("age");
System.out.println("Name: " + name + ", Age: " + age);
} } catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (statement != null) {
statement.close();
} if (connection != null) {
connection.close();
} } catch (SQLException e) {
e.printStackTrace();
} } }}
23
5) Close the connection object
By closing connection object statement and ResultSet will be closed
automatically. The close() method of Connection interface is used to close the
connection.

Syntax of close() method

public void close()throws SQLException

Example : con.close();

JDBC example

24
oPreparedStatement interface

The PreparedStatement interface is a subinterface of Statement. It


is used to execute parameterized query.

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


As you can see, we are passing parameter (?) for the values. Its value will be
set by calling the setter methods of PreparedStatement.

Example1

25
statement = connection.createStatement();
String insertSql = "INSERT INTO customers (name, age)
VALUES (‘abdi jemal’, 20)";
statement.executeUpdate(insertSql);
String updateSql = "UPDATE customers SET age = 21
WHERE name = ‘abdi jemal’";
statement.executeUpdate(updateSql);
String deleteSql = "DELETE FROM customers WHERE name
= ‘abdi jemal'";
statement.executeUpdate(deleteSql);
System.out.println("CRUD operations completed
successfully!");
} catch (Exception e) {
}
26
oResultSetMetaData Interface
The metadata means data about data i.e. we can get further information from
the data. If you have to get metadata of a table like total number of column,
column name, column type etc. , ResultSetMetaData interface is useful
because it provides methods to get metadata from the ResultSet object.

The getMetaData() method of ResultSet interface returns the object of


ResultSetMetaData.

Syntax: public ResultSetMetaData getMetaData()throws SQLException

27
oResultSetMetaData Interface
Method Description
public int getColumnCount()throws it returns the total number of columns
SQLException in the ResultSet object.
public String getColumnName(int it returns the column name of the
index)throws SQLException specified column index.

public String getColumnTypeName(int it returns the column type name for


index)throws SQLException the specified index.

public String getTableName(int it returns the table name for the


index)throws SQLException specified column index.

Example1 Example2
28
statement = connection.createStatement();

resultSet = statement.executeQuery("SELECT * FROM employees");


ResultSetMetaData metaData = resultSet.getMetaData();

int columnCount = metaData.getColumnCount();

for (int i = 1; i <= columnCount; i++) {

System.out.println("Column Name: " + metaData.getColumnName(i));


System.out.println("Column Type: " + metaData.getColumnTypeName(i));
System.out.println("Column Size: " + metaData.getColumnDisplaySize(i));
System.out.println("Is Nullable: " + metaData.isNullable(i));

System.out.println("----------");

29
oDatabaseMetaData interface
DatabaseMetaData interface provides methods to get meta data of a database
such as database product name, database product version, driver name, name
of total number of tables, name of total number of views etc.

The getMetaData() method of Connection interface returns the object of


DatabaseMetaData.

Syntax: public DatabaseMetaData getMetaData()throws SQLException

30
omethods of DatabaseMetaData interface
public String getDriverName()throws SQLException: it returns the
name of the JDBC driver.
public String getDriverVersion()throws SQLException: it returns the
version number of the JDBC driver.
public String getUserName()throws SQLException: it returns the
username of the database.
public String getDatabaseProductName()throws SQLException: it
returns the product name of the database.
public String getDatabaseProductVersion()throws SQLException: it
returns the product version of the database.
public ResultSet getTables(String catalog, String schemaPattern,
String tableNamePattern, String[] types)throws SQLException: it
returns the description of the tables of the specified catalog. The table
type can be TABLE, VIEW, ALIAS, SYSTEM TABLE, SYNONYM etc.
Example
31
// Get DatabaseMetaData object

DatabaseMetaData metaData = connection.getMetaData();

// Retrieve database information

System.out.println("Database Product Name: " +


metaData.getDatabaseProductName());

System.out.println("Database Product Version: " +


metaData.getDatabaseProductVersion());

System.out.println("Driver Name: " + metaData.getDriverName());

System.out.println("Driver Version: " + metaData.getDriverVersion());

System.out.println("Database URL: " + metaData.getURL());

System.out.println("Supports Transactions: " + metaData.supportsTransactions());


32
ResultSet tablesResultSet = metaData.getTables(null, null, null, new String[] { "TABLE" });
while (tablesResultSet.next()) { String tableName =
tablesResultSet.getString("TABLE_NAME");
System.out.println("- " + tableName); }
// Retrieve columns information for a specific table
ResultSet columnsResultSet = metaData.getColumns(null, null, "employees", null);
System.out.println("Columns of employees table:");
while (columnsResultSet.next()) { String columnName =
columnsResultSet.getString("COLUMN_NAME");
String columnType = columnsResultSet.getString("TYPE_NAME");
int columnSize = columnsResultSet.getInt("COLUMN_SIZE");
System.out.println("- Name: " + columnName + ", Type: " + columnType + ", Size: " +
columnSize); } 33
34

You might also like