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

02 JDBC

JDBC is an interface that allows Java programs to connect to and interact with various databases. It provides standard APIs for establishing a connection with a database, executing queries, and processing result sets. The typical flow of using JDBC involves loading the appropriate JDBC driver, creating a connection, executing statements to query or manipulate data, processing any result sets, and closing the connection. Vendors implement the JDBC interfaces in their own drivers to allow communication with their specific database products.

Uploaded by

FuadNaserAl-deen
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)
38 views30 pages

02 JDBC

JDBC is an interface that allows Java programs to connect to and interact with various databases. It provides standard APIs for establishing a connection with a database, executing queries, and processing result sets. The typical flow of using JDBC involves loading the appropriate JDBC driver, creating a connection, executing statements to query or manipulate data, processing any result sets, and closing the connection. Vendors implement the JDBC interfaces in their own drivers to allow communication with their specific database products.

Uploaded by

FuadNaserAl-deen
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

• JDBC is a collection of interfaces serving as an integration protocol with


various existing databases (DBs).

• For the vendor, JDBC is a standard that must be supported.

• Each vendor may implement the interfaces in his own way


(either by using a driver or by using an extra layer called a JDBC bridge).
JDBC

There are 4 different drivers, each suitable for a different purpose.

Type 1- ODBC Drivers-DBC is a JDBC bridge that allows, among other things,
integration of Java code with a variety of DBs it supports
(such as: SQL Servers, AccessOracle, etc.)
Type 2 - Native Drivers- Drivers of this type are written in languages such as
C or C++ and allow fast integration with the various DB they are written for

Type 3 - Network drivers – the use of drivers of this kind is appropriate for
clients that want to connect to a DB through a network.

Type 4 - Java drivers – any driver written in Java. These drivers require no
client side installation, since they are written in Java, however, they may
have some performance problems.
JDBC
JDBC API consists of the following main components:

JDBC
1. JDBC Driver

2. Connection

3. Statement

4. ResultSet
A JDBC driver is set of Java classes that implement JDBC
interfaces for interacting with a specific database.

JDBC
Almost all database vendors such as MySQL, Oracle,
Microsoft SQL Server, provide JDBC drivers. 

MySQL provides a JDBC driver called MySQL


JDBC Driver Connection/J that allows you to work with MySQL
database through a standard JDBC API.

There are three types of JDBC drivers including


• JDBC-native API Driver
• JDBC-net Driver
• JDBC Driver.

JDBC Driver is written in pure Java , It translates JDBC


calls into MySQL specific calls and sends the calls
directly to a specific database. 
The first and most important component of JDBC is the
JDBC Connection object. 

Connection Through the Connection object, Java/DB GUI can interact with
the database for creating a Statement to execute SQL queries
against tables.

more than one connection can be opened to a database at a


time.
The statement Object is used to execute SQL Queries like

• SELECT
JDBC • INSERT
• UPDATE
• DELETE

Statement Statement object is created through the Connection object.

JDBC provides several types of statements for different


purposes such as PreparedStatement , CallableStatement
JDBC
The ResultSet object provides a set of API that allows you to traverse result
of the query.

ResultSet
ResultSet is getting After querying data from the database
The typical flow of using JDBC is as follows:

• load the JDBC driver and create a connection to the database.


JDBC
• create a Statement and execute the query to get a ResultSet.

• traverse and process the ResultSet .

JDBC Flow • Close the ResultSet , Statement , and Connection .


Download the Jar

JDBC
Load the mysql-connector-Java

Connecting to MySQL Using


JDBC Driver
• Choose the Libraries panel

• Choose the Add External Jar Option and bring the relevant Jar from the local

JDBC

Connecting to MySQL Using


JDBC Driver
• Click on the Apply and Close

JDBC

Connecting to MySQL Using


JDBC Driver
Connecting to MySQL database

JDBC 1- Import three classes:

• SQLException

• DriverManager
Connecting to MySQL Using
JDBC Driver • Connection

from the java.sql.* package.


Connecting to MySQL database

2- call the getConnection() method of the DriverManager class to


JDBC get the Connection object.

There are three parameters you need to pass to the


Connecting to MySQL Using
getConnection() method:
JDBC Driver

1.url:
the database URL in the form jdbc:subprotocol:subname.
For MySQL, you use the jdbc:mysql://localhost:3306/mysqljdbc

2.user: the database user that will be used to connect to


MySQL.

3.password: the password of the database user.


Connecting to MySQL database

JDBC

Connecting to MySQL Using


JDBC Driver
Connecting to MySQL database

JDBC • When connecting to MySQL, anything could happens e.g., database


server is not available, wrong user name or password, etc.

• in such cases, JDBC throws a SQLException .


Connecting to MySQL Using
• Therefore, when you create a Connection object, you should always put
JDBC Driver it inside a try catch block.

• Also you should always close the database connection once you
complete interacting with database by calling close() method of the
Connection object.
Connecting to MySQL database

From Java 7, there is another nice statement called try-with-resources that


JDBC allows you to simplify the code above as follows:

Connecting to MySQL Using


JDBC Driver

• It is automatically calls the close() method of the Connection object once


program finishes.
• But, It is not secure as well as flexible when you hard coded the database
parameters inside the code like above.
Connecting to MySQL database
• To avoid hard coding all the database parameters in the code,
you can use a Java properties file to store them.
• In case of changes, you just need to change them in the
JDBC properties file and you don’t have to recompile the code.

Connecting to MySQL Using


JDBC Driver
Connecting to MySQL database

JDBC

Connecting to MySQL Using


JDBC Driver

• For each interaction with MySQL


database, you need to create a new
connection.

• You would have the same piece of


code for doing this in all places.
Rather than doing this, you can
create a new class for handing
connection creation
Connecting to MySQL database

JDBC

Connecting to MySQL Using


JDBC Driver

• For each interaction with MySQL


database, you need to create a new
connection.

• You would have the same piece of


code for doing this in all places.
Rather than doing this, you can
create a new class for handing
connection creation
Querying Data From MySQL Using JDBC

JDBC

execute: execute all queries types , return true if ResultSet is created


Querying Data From MySQL Using ,else it returns false.
JDBC

executeQuery : returns the ResultSet Object for select Queries

executeUpdate: execute SQL queries which updating the DB,


returns the affected records.
Querying Data From MySQL Using JDBC

• After opening the connection, you need to create a Statement object.


JDBC • JDBC provides several kinds of statements such as Statement,
PreparedStatement and CallableStatement.

• For querying data, you just need to use the Statement object as follows:
Querying Data From MySQL Using
JDBC Statement stmt  = conn.createStatement();

Once you have a Statement object created, you can use it to execute any
valid MySQL query like the following:

String sql = "SELECT first_name, last_name, email FROM candidates";


executeQuery  
ResultSet rs    = stmt.executeQuery(sql)

• The executeQuery() method of the Statement returns a ResultSet


object that contains result of the SQL query.

• The result is in the form of rows with columns of data based on the
SELECT statement.
Querying Data From MySQL Using JDBC

• The ResultSet object provides you with methods to traverse the result and
read the data.
JDBC • The next() method returns true and move to the next row in the ResultSet
if there are rows available, otherwise it returns false.

• You must call the next() method at least one before reading data
because before the first next() call, the ResultSet is located before the
Querying Data From MySQL Using
first row.
JDBC while (rs.next()) {
System.out.println(rs.getString("first_name") + "\t" +
rs.getString("last_name") + "\t" +
rs.getString("email"));
}
executeQuery
• Use the getDataType() method to get column data of the current row
where DataType is the data type of the column

• You need to pass the column name or column index to the


getDataType() method
String s = rs.getString("column_name");
int id = rs.getInt(1);
Querying Data From MySQL Using JDBC

JDBC

Querying Data From MySQL Using


JDBC

executeQuery
Querying Data From MySQL Using JDBC

JDBC The PreparedStatement interface extends the Statement interface that


provides some more advanced features as follows:

• Add parameters into you SQL statement using placeholders in the form
of question marks (?). This helps you avoid SQL injection.
Querying Data From MySQL Using
JDBC • Reuse the PreparedStatement with new parameters in case you need to
execute the SQL statement multiple times with different parameters.

• Help increase performance of the executed statement by precompiling


the SQL statement.
PreparedStatement
Querying Data From MySQL Using JDBC

JDBC • create PreparedStatement object by calling the prepareStatement()


method of the Connection object.

• The prepareStatement() method accepts various parameters.


Querying Data From MySQL Using
JDBC

you supply values for the placeholders one-by-one by using setYYY()


PreparedStatement method of the PreparedStatement interface where YYY is the data
type of the placeholder.
Querying Data From MySQL Using JDBC

• Send the executed statement with the values for the placeholders to
JDBC MySQL by calling executeUpdate() method of the PreparedStatement
interface.

• This method takes no arguments and returns the number of row affected.

Querying Data From MySQL Using int rowAffected = pstmt.executeUpdate();


JDBC

PreparedStatement
JDBC

Querying Data From MySQL Using


JDBC

PreparedStatement
Setting auto-commit mode

• The auto-commit mode is set to true by default.


JDBC • In case you want to control when to commit the transaction, you call
the setAutoCommit() method of the Connection object as follows:

Connection conn = DriverManager.getConnection(dbURL,dbUser,dbPassword);


conn.setAutoCommit(false);
MySQL JDBC Transaction

• Committing and rolling back a transaction


Thank You

You might also like