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

JDBC

Uploaded by

Kannan A
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)
24 views59 pages

JDBC

Uploaded by

Kannan A
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/ 59

JDBC

Dr.A.Kannan
Continuous Assessment Test
(Lab)
• 19.11.2021 Friday
• Syllabus SQL Queries
Overview of Databases and
Java
RMI JDBC CORBA

java.net

TCP/IP

Network OS
N-Tier Architecture
• Design your application using as many
“tiers” as you need
• Use Object-Oriented Design techniques
• Put the various components on whatever
host makes sense
• Java allows N-Tier Architecture, especially
with RMI and JDBC
JDBC Architecture

Application JDBC Driver

• Java code calls JDBC library


• JDBC loads a driver
• Driver talks to a particular database
• Can have more than one driver -> more than
one database
• Ideal: can change database engines without
changing any application code
JDBC Drivers
• Type I: “Bridge”
• Type II: “Native”
• Type III: “Middleware”
• Type IV: “Pure”
JDBC Drivers (Fig.)

Type I ODBC
ODBC
“Bridge” Driver

Type II
JDBC CLI (.lib)
“Native”

Type III Middleware


“Middleware” Server

Type IV
“Pure”
Type I Drivers
• Use bridging technology
• Requires installation/configuration on
client machines
• Not good for Web
• e.g. ODBC Bridge
Type II Drivers
• Native API drivers
• Requires installation/configuration on
client machines
• Used to leverage existing CLI libraries
• Usually not thread-safe
• Mostly obsolete now
• e.g. Intersolv Oracle Driver, WebLogic
drivers
Type III Drivers
• Calls middleware server, usually on
database host
• Very flexible -- allows access to multiple
databases using one driver
• Only need to download one driver
• But it’s another server application to install
and maintain
• e.g. Symantec DBAnywhere
Type IV Drivers
• 100% Pure Java -- the Holy Grail
• Use Java networking libraries to talk
directly to database engines
• Only disadvantage: need to download a
new driver for each database engine
• e.g. Oracle, mSQL
JDBC Limitations
• No scrolling cursors
• No bookmarks
Six Steps to Using JDBC
1. Load the JDBC Driver
2. Establish the Database Connection
3. Create a Statement Object
4. Execute a Query
5. Process the Results
6. Close the Connection
1) Loading the JDBC Driver
• To use a JDBC driver,
– you must load the driver via the
Class.forName() method.
• In general, the code looks like this:
Class.forName("jdbc.DriverXYZ");
– where jbdc.DriverXYZ is the JDBC Driver
you want to load.
• To use MySQL and load jdbc driver:
Class.forName(”com.mysql.odbc.driver");
1) Loading the JDBC Driver- Cont…
• To use ORACLE and load jdbc driver:
Class.forName(”oracle.odbc.driver.Oracle
Driver");
• If you are using SUN JDBC-ODBC Driver,
your code will look like this:
Class.forName("sun.jdbc.odbc.JdbcOdbcD

river");
Loading the MySQL Driver
• If you are using the MySQL Driver, your code will look
like this:
try {
Class.forName("com.mysql.jdbc.Driver"); }
catch(java.lang.ClassNotFoundException e)

{ System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage());
}
• Class.forName() will throw a ClassNotFoundException
if your CLASSPATH is not set up properly.
2) Establish the Connection
• Once you have loaded your JDBC driver, the
next step is to establish a database
connection.
• The following line of code illustrates the basic
idea:
Connection con =
DriverManager.getConnection(url);
Creating a Connection URL
• The only difficulty in establishing a connection
is specifying the correct URL.
• In general, the URL has the following format:
jdbc:subprotocol:subname.
– JDBC indicates that this is a JDBC
Connection (no mystery there!)
– The subprotocol identifies the driver you want
to use.
– The subname identifies the database
name/location.
Connection URL: ODBC
• For example, the following code uses a
JDBC-ODBC bridge to connect to the local
Fred database:
String url = "jdbc:odbc:Fred";
Connection con =
DriverManager.getConnection(url,
“username", "password");
3) Create a Statement Object
• The JDBC Statement object sends SQL
statements to the database.
• Statement objects are created from active
Connection objects.
• For example:
– Statement stmt = con.createStatement();
• With a Statement object, you can issue SQL
calls directly to the database.
4) Execute a Query
• executeQuery()
– Executes the SQL query and returns the
data in a table (ResultSet)
– The resulting table may be empty but never
null
ResultSet results = stmt.
executeQuery("SELECT a, b FROM table");
4) Execute a Query-Cont…
• executeUpdate()
– Used to execute for INSERT, UPDATE, or
DELETE SQL statements
– The return is the number of rows that were
affected in the database
– Supports Data Definition Language (DDL)
statements
CREATE TABLE, DROP TABLE and ALTER
TABLE
Useful Statement Methods
• getMaxRows/setMaxRows
– Determines the number of rows a ResultSet
may contain
– Unless explicitly set, the number of rows are
unlimited (return value of 0)

• getQueryTimeout/setQueryTimeout
– Specifies the amount of a time a driver
will wait for a STATEMENT to complete
before throwing a SQLException
5) Process the Results
• A ResultSet contains the results of the SQL
query.
• All methods can throw a SQLException
• Useful Methods
– close
– getMetaDataObject
• Returns a ResultSetMetaData object
containing information about the columns
in the ResultSet
ResultSet (Continued)
• next
• Attempts to move to the next row in
the ResultSet
–If successful true is returned;
–otherwise, false
–The first call to next positions the
cursor a the first row
6) Close the Connection
• To close the database connection:
– stmt.close();
– connection.close();
JDBC Example
• Setting Up Tables via JDBC
• Inserting Data via JDBC
• Querying Data via JDBC
• JDBC Exception Handling
The Coffee Tables
• To get started, we will first examine JDBC code for
creating new tables.
• This java code for creating this table will create a
table for storing data:
CREATE TABLE COFFEES
(COF_NAME VARCHAR(32),
SUP_ID INTEGER,
PRICE FLOAT,
SALES INTEGER,
TOTAL INTEGER);
The Coffees Tables
COF_NAME SUP_ID PRICE SALES TOTAL

Colombian 101 7.99 0 0

French_Roast 49 8.99 0 0

Espresso 150 9.99 0 0

Colombian_Decaf 101 8.99 0 0

French_Roast_Decaf 49 9.99 0 0
JDBC Example
• Setting Up Tables via JDBC
• Inserting Data via JDBC
• Querying Data via JDBC
• JDBC Exception Handling
import java.sql.*;

public class CreateCoffees {


public static void main(String args[]) {
String url = "jdbc:mysql://localhost/coffee";
Connection con; String createString;
createString = "create table COFFEES " +
"(COF_NAME VARCHAR(32), " +
"SUP_ID INTEGER, " + "PRICE FLOAT, "

+"SALES INTEGER, " + "TOTAL


INTEGER)";
Statement stmt;
try
{ Class.forName("com.mysql.jdbc.Driver")
; } catch(java.lang.ClassNotFoundException e)
{
System.err.print("ClassNotFoundException: );
System.err.println(e.getMessage()); }
try {
con = DriverManager.getConnection(url);
stmt = con.createStatement();
stmt.executeUpdate(createString);
stmt.close(); con.close();
} catch(SQLException ex) {
System.err.println("SQLException: " +
JDBC Example
• Setting Up Tables via JDBC
• Inserting Data via JDBC
• Querying Data via JDBC
• JDBC Exception Handling
import java.sql.*;
public class InsertCoffees {
public static void main(String args[]) throws
SQLException
{ System.out.println ("Adding Coffee Data");
ResultSet rs = null;
PreparedStatement ps = null;
String url = "jdbc:mysql://localhost/coffee";
Connection con; Statement stmt;
try { Class.forName("com.mysql.jdbc.Driver"); }

catch(java.lang.ClassNotFoundException e)
{System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage()); }
try { con = DriverManager.getConnection(url);
stmt = con.createStatement();
stmt.executeUpdate ("INSERT INTO
COFFEES " +VALUES('Amar', 49, 9.99, 0, 0)”);
stmt.executeUpdate ("INSERT INTO COFFEES

" + "VALUES('Hazelnut', 49, 9.99, 0, 0)");


stmt.executeUpdate ("INSERT INTO COFFEES
" + "VALUES('Amar_decaf', 49, 10.99, 0, 0)");
stmt.executeUpdate ("INSERT INTO COFFEES
" + "VALUES('Hazel_decaf', 49, 10.99, 0, 0)");
stmt.close(); con.close();
System.out.println ("Done");
} catch(SQLException ex) { }
JDBC Example
• Setting Up Tables via JDBC
• Inserting Data via JDBC
• Querying Data via JDBC
• JDBC Exception Handling
import java.sql.*;
public class SelectCoffees
{ public static void main(String args[]) throws
SQLException {
ResultSet rs = null;
PreparedStatement ps = null;
String url = "jdbc:mysql://localhost/coffee";
Connection con; Statement stmt;
try { Class.forName("com.mysql.jdbc.Driver"); }
catch(java.lang.ClassNotFoundException e)
{ System.err.print("ClassNotFoundException: ");
System.err.println(e.getMessage()); }
try { con = DriverManager.getConnection(url);
stmt = con.createStatement();
ResultSet uprs = stmt.execute
Query("SELECT * FROM COFFEES")

System.out.println("Table COFFEES:");
While (uprs.next()) {
String name =uprs.getString("COF_NAME");
int id = uprs.getInt("SUP_ID");
float price = uprs.getFloat("PRICE");
int sales = uprs.getInt("SALES");
int total = uprs.getInt("TOTAL");
System.out.print(name + " " + id + " " +
price);
System.out.println(" " + sales + " " + total); }
uprs.close(); stmt.close(); con.close();
JDBC Example
• Setting Up Tables via JDBC
• Inserting Data via JDBC
• Querying Data via JDBC
• JDBC Exception Handling
Exception Handling
• SQL Exceptions
– every JDBC method can throw a SQL
Exception in response to a data access error
– If more than one error occurs, they are
chained together
• SQL exceptions contain:
• Description of the error, getMessage
• The SQLState identifying the exception,
getSQLState
• A vendor-specific integer, error code,
getErrorCode
• A chain to the next SQLException,
getNextException
SQL Exception Example
try {
... // JDBC statement.
} catch (SQLException sqle) {
while (sqle != null)
{ System.out.println("Message:"+sqle.getM
ess
age());
System.out.println("SQLState:" +
sqle.getSQLState());
System.out.println("Vendor Error:"+
sqle.getErrorCode());
sqle.printStrackTrace(System.out);
sqle = sqle.getNextException();
} }
Using Prepared Statements
• Until now we have seen JDBC Statement
objects for querying/updating tables.
• The PreparedStatement object provides similar
functionality and provides two additional
benefits:
– Faster execution
– Parameterized SQL Statements
Creating a PreparedStatement
Object
• As with Statement objects, you create a
PreparedStatement object with a Connection
method.
• For example:
PreparedStatement updateSales =
con.prepareStatement(
"UPDATE COFFEES SET SALES = ? WHERE
COF_NAME LIKE ?");
• In this example, the ? indicates a parameter
placeholder which can be set via the JDBC API.
Setting Parameters
• Once you have your PreparedStatement, you
need to supply parameter values for each of the
question mark placeholders.
• You do this by calling one of the setXXX methods
defined in the PreparedStatement API.
– If the value you want to substitute for a question
mark is a Java int, you call the setInt() method.
– If the value you want to substitute for a question
mark is a Java String, you call the
setString()method.
– In general, there is a setXXX method for each
type in the Java programmingLanguage
Setting Parameters: Example
• These two code fragments accomplish the same
thing: Code Fragment 1:
String updateString = "UPDATE COFFEES SET
SALES = 75 " + "WHERE COF_NAME
LIKE 'Colombian'";
stmt.executeUpdate(updateString);
Code Fragment 2:
PreparedStatement updateSales = con.
prepareStatement("UPDATE COFFEES SET
SALES = ? WHERE COF_NAME LIKE ?");
updateSales.setInt(1, 75);
updateSales.setString(2, "Colombian");
updateSales.executeUpdate():
Executing a Prepared Statement
• To execute a PreparedStatement:
– executeUpdate()
– executeQuery()
• Same as a regular Statement, except that
no SQL String parameter is specified
(because it has already been specified.)
Using a Loop to Set Values
• You can often make coding easier by using a for
loop or a while loop to set values for input
parameters.
• The next code fragment illustrates the basic idea:
– One PreparedStatement is created.
– A for loop runs 5 times. Each time through, the
code sets a new value and executes the SQL
statement.
– Updates sales for 5 different coffees .
For Loop Example
PreparedStatement updateSales;
String updateString = "update COFFEES " +
"set SALES = ? where COF_NAME like ?";
updateSales = con.prepareStatement(updateString);
int [ ] salesForWeek = {175, 150, 60, 155, 90};
String [ ] coffees = {"Colombian","French_Roast",
"Espresso", Colombian_Decaf",
"French_Roast_Decaf"};
int len = coffees.length;
for(int i = 0; i < len; i++) {
updateSales.setInt(1, salesForWeek[i]);
updateSales.setString(2, coffees[i]);
updateSales.executeUpdate(); }
Using Transactions
• A transaction is a set of one or more
statements that are executed together as
a unit.
• Hence, either all of the statements are
executed, or none of the statements are
executed.
Disabling Auto-Commit Mode
• When a connection is created, it is in auto-
commit mode.
• This means that each individual SQL statement
is treated as a transaction and will be
automatically committed right after it is executed.
• The way to allow two or more statements to be
grouped into a transaction is to disable auto-
commit mode.

con.setAutoCommit(false);
Committing a Transaction
• Once auto-commit mode is disabled, no SQL
statements will be committed until you call the
commit() method explicitly.
• All statements executed after the previous call to
the method commit will be included in the
current transaction and will be committed
together as a unit.
• The code on the next slide illustrates the basic
idea.
Transaction Action
con.setAutoCommit(false);
PreparedStatement updateSales = con.
prepareStatement("UPDATE COFFEES SET
SALES = ? WHERE COF_NAME LIKE ?");
updateSales.setInt(1, 50);
updateSales.setString(2, "Colombian");
updateSales.executeUpdate();
PreparedStatement updateTotal =con. Prepare
Statement("UPDATE COFFEES SET TOTAL =
TOTAL + ? WHERE COF_NAME LIKE ?");
Transaction Action-Cont…
updateTotal.setInt(1, 50);
updateTotal.setString(2, "Colombian");
updateTotal.executeUpdate();
con.commit(); con.setAutoCommit(true);
Rolling Back
• To cancel a transaction, call the rollback()
method.
• This aborts the transaction and restores values
to what they were before the attempted update.
• If you are executing multiple statements within
a transaction, and one of these statements
generates a SQLException, you should call the
rollback() method to abort the transaction and
start over again.
import java.sql.*;
public class TransactionPairs {
public static void main(String args[ ])
{ String url = "
jdbc:mysql://localhost/databasename";
Connection con = null; Statement stmt;
PreparedStatement updateSales,updateTotal;
String updateString = "update COFFEES " +
"set SALES = ? where COF_NAME = ?";
String updateStatement = "update COFFEES "
+ "set TOTAL = TOTAL + ? where
COF_NAME = ?";
String query = "select COF_NAME,”+
“SALES, TOTAL from COFFEES";
try {
Class.forName("com.mysql.jdbc.Driver"); }
catch(java.lang.ClassNotFoundException e)
{
System.err.print("ClassNotFoundException");
System.err.println(e.getMessage()); }
try
{ con = DriverManager.getConnection(url,
"myLogin", "myPassword");
updateSales =
con.prepareStatement(updateString);
updateTotal =
con.prepareStatement(updateStatement)
int [ ] salesForWeek = {175, 150, 60, 155, 90};
String [] coffees = {"Colombian",
"French_Roast", "Espresso",
"Colombian_Decaf","French_Roast_Decaf"};
int len = coffees.length;
con.setAutoCommit(false);
for (int i = 0; i < len; i++) {
updateSales.setInt(1, salesForWeek[i]);
updateSales.setString(2, coffees[i]);
updateSales.executeUpdate();
updateTotal.setInt(1, salesForWeek[i]);
updateTotal.setString(2, coffees[i]);
updateTotal.executeUpdate();
con.commit(); }
con.setAutoCommit(true);
updateSales.close(); updateTotal.close();
} catch(SQLException ex) {
System.err.println("SQLException: " +
ex.getMessage());
if (con != null) {
try {
System.err.print("Transaction is being ")
System.err.println("rolled back");
con.rollback();
} catch(SQLException excep) {
System.err.print("SQLException: ");
System.err.println(excep.getMessage());
Summary
• The JDBC API defines interfaces and
classes for writing database applications
.
in Java by making database connections.

• Program developed with Java and JDBC


are “platform independent” and “vendor
independent”

You might also like