0% found this document useful (0 votes)
24 views24 pages

Intro To JDBC

The document discusses how to connect to a database and execute queries using JDBC in Java. It describes establishing a connection, creating statements to execute queries, processing result sets, and closing connections. Key aspects covered include using prepared statements with placeholders, handling null values, and mapping database types to Java types.

Uploaded by

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

Intro To JDBC

The document discusses how to connect to a database and execute queries using JDBC in Java. It describes establishing a connection, creating statements to execute queries, processing result sets, and closing connections. Key aspects covered include using prepared statements with placeholders, handling null values, and mapping database types to Java types.

Uploaded by

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

Java

Database Connectivity
(JDBC)

Prepared by : Elen T. Capariño


JDBC

 JDBC is a standard interface for connecting to


relational databases from Java.
 The JDBC classes and interfaces are in the
java.sql package.
 JDBC 1.22 is part of JDK 1.1; JDBC 2.0 is part of
Java 2
Overview of Querying a Database With JDBC

Connect

Query

Process
results

Close
Stage 1: Connect

Connect Register the driver

Query Connect to the database

Process
results

Close
A JDBC Driver
 Is an interpreter that translates JDBC
method calls to vendor-specific database
commands

Database
JDBC calls commands
Driver
Database

 Implements interfaces in java.sql


 Can also provide a vendor’s extensions to
the JDBC standard
About JDBC URLs
 JDBC uses a URL to identify the database
connection.
jdbc:<subprotocol>:<subname>

Database
Protocol Subprotocol
identifier

jdbc:oracle:<driver>:@<database>

Example: jdbc:mysql://localhost:3306/
How to Make the Connection
1. Load JDBC Driver
Class.forName(driver);

Class.forName(driver);
// or
Class.forName("com.mysql.jdbc.Driver");

2. Connect to the database


Connection conn = DriverManager.getConnection
(URL, userid, password);

Connection conn = DriverManager.getConnection


(url + dbName, userName, password);
Example of establishing a connection
Stage 2: Query

Connect

Query Create a statement

Process Query the database


results

Close
The Statement Object
 A Statement object sends your SQL
statement to the database.
 You need an active connection to create
a JDBC statement.
 Statement has three methods to execute
a SQL statement:
– executeQuery() for QUERY
statements
– executeUpdate() for INSERT,
UPDATE, DELETE, or DDL
statements
– execute() for either type of statement
How to Query the Database

1. Create an empty statement object.


Statement stmt = conn.createStatement();

2. Execute the statement.


ResultSet rset = stmt.executeQuery(statement);
int count = stmt.executeUpdate(statement);
boolean isquery = stmt.execute(statement);
Querying the Database: Examples
 Execute a select statement.
Statement stmt = conn.createStatement();
ResultSet rset = stmt.executeQuery
("select RENTAL_ID, STATUS from ACME_RENTALS");

• Execute a delete statement.


Statement stmt = conn.createStatement();
int rowcount = stmt.executeUpdate
("delete from ACME_RENTAL_ITEMS where rental_id = 1011");
Stage 3: Process the Results

Connect

Query
Step through the results

Process Assign results to Java


results variables

Close
The ResultSet Object
 JDBC returns the results of a query in a
ResultSet object.
 A ResultSet maintains a cursor pointing to
its current row of data.
 Use next() to step through the result set
row by row.
 getString(), getInt(), and so on assign
each value to a Java variable..
How to Process the Results
 1. Step through the result set.

while (rset.next()) { … }

 2. Use getXXX() to get each column value.

String val = String val =


rset.getString(colname); rset.getString(colIndex);

while (rset.next()) {
String title = rset.getString("TITLE");
String year = rset.getString("YEAR");
… // Process or display the data
}
How to Handle SQL Null Values
 Java primitive types cannot have null
values.
 Do not use a primitive type when your
query might return an SQL null.
 Use ResultSet.wasNull() to determine
whether a column has a null value.
while (rset.next()) {
String year = rset.getString("YEAR");
if (rset.wasNull() {
… // Handle null value
}
…}
Mapping Database Types to Java Types
 ResultSet maps database types to
Java types.
ResultSet rset = stmt.executeQuery
("select RENTAL_ID, RENTAL_DATE, STATUS
from ACME_RENTALS");

int id = rset.getInt(1);
Date rentaldate = rset.getDate(2);
String status = rset.getString(3);
Col Name Type

RENTAL_ID NUMBER

RENTAL_DATE DATE

STATUS VARCHAR2
Stage 4: Close

Connect

Query
Close the result set

Process
results Close the statement

Close Close the connection


How to Close the Connection
1. Close the ResultSet object.
rset.close();

2. Close the Statement object.


stmt.close();

3. Close the connection (not necessary


for server-side driver).
conn.close();
The PreparedStatement Object

• A PreparedStatement object
holds precompiled SQL statements.
• Use this object for statements you want
to execute more than once.
• A prepared statement can contain
variables that you supply each time
you execute the statement.
How to Create a Prepared Statement
1.Register the driver and create the database
connection.
2.Create the prepared statement, identifying
variables with a question mark (?).

PreparedStatement pstmt =
conn.prepareStatement("update ACME_RENTALS
set STATUS = ? where RENTAL_ID = ?");

PreparedStatement pstmt =
conn.prepareStatement("select STATUS from
ACME_RENTALS where RENTAL_ID = ?");
How to Create a Prepared Statement
1.Register the driver and create the
database connection.
2.Create the prepared statement,
identifying variables with a question
mark (?).
Example :
PreparedStatement pstmt = conn.prepareStatement
("select STATUS from ACME_RENTALS where RENTAL_ID = ?");

PreparedStatement ps = null;
ps = conn.prepareStatement("INSERT INTO tbl_product (key_product, key_category,
fld_product_name, fld_inventory_qty, fld_unit_price) “ + "values (?, ?, ?, ?, ?)");
How to Execute a Prepared Statement
1. Supply values for the variables.
pstmt.setXXX(index, value);

2. Execute the statement.


pstmt.executeQuery();
pstmt.executeUpdate();

Example : ps.setLong(1, product.getKey_product());


ps.setLong(2, product.getKey_category());
ps.setString(3, product.getFld_product_name());
ps.setInt(4, product.getFld_inventory_qty());
ps.setInt(5, (int) product.getFld_unit_price());

ps.executeUpdate();
A Simple JDBC Program…

You might also like