Upload
priyajoish
View
225
Download
0
Embed Size (px)
Citation preview
8/6/2019 Session 10- JDBC
1/53
Java Database ConnectivityJava Database Connectivity
8/6/2019 Session 10- JDBC
2/53
AgendaAgenda
y Basics & Introduction
y JDBC Goals
y JDBC Architecture
y Databasesy The JDBC Drivers & Types of Drivers
y The Basic Steps of JDBC Application
y Prepared Statements & Callable Statements
y The Transactions & Commitment controly Resources
8/6/2019 Session 10- JDBC
3/53
3
JDBCJDBC - Basics
JDBC is a Java language common database
programming API that provides easy access to theDatabase for all the DDL and DML operations.
JDBC provides a standard library for accessing
relational databases.
As well the application developed for certain databasecan be easily configured for other databases.
8/6/2019 Session 10- JDBC
4/53
IntroductionIntroduction
y JDBC API standardizes
Way to establish connection to database
Approach to initiating queries
Method to create stored (parameterized) queries
The data structure of query result (table)
y JDBC API does not standardize SQL syntax
y JDBC classes are in the java.sql & javax.sqlpackages
8/6/2019 Session 10- JDBC
5/53
JDBC GoalsJDBC Goals
y SQL-Levely 100% Pure Javay Simple to incorporate
y High-performancey Leverage existing database technologyy Reusability
8/6/2019 Session 10- JDBC
6/53
Why100% JAVA ??Why100% JAVA ??
y Write once, run anywhere - Multiple client and server platforms
y Object-relational mapping
databases optimized for searching/indexing
objects optimized for engineering/flexibility
y Network independence - Works across Internet Protocol
y Database independence - Java can access any database vendor
y Ease of administration - zero-install client
8/6/2019 Session 10- JDBC
7/53
JDBC ArchitectureJDBC Architecture
y Java code calls JDBC library
y JDBC loads a driver
y Driver talks to a particular database
y Ability to have more than one driver to more than one database
y Flexibility to change database engines without changing any application
code
Application JDBC Driver
8/6/2019 Session 10- JDBC
8/53
JDBC ArchitectureJDBC Architecture
8/6/2019 Session 10- JDBC
9/53
Copyright 1997Alex Chaffee
RelationalDatabasesRelationalDatabases
y Invented by Dr. E.F.Coddy Data stored in recordswhich live in tablesy Maps row(record) to column(field) in a
single tabley relation (as in relational) means row to
column (not table to table)
yRelational (SQL) (RDBMS) row, column
most popular
8/6/2019 Session 10- JDBC
10/53
Copyright 1997Alex Chaffee
SQLSQL
y Structured Query Language
y Standardized syntax for querying (accessing) arelational database
y
Supposedly database-independenty Actually, there are important variations from DB
to DB
8/6/2019 Session 10- JDBC
11/53
Copyright 1997Alex Chaffee
SQLSyntaxSQLSyntaxINSERT INTO table ( field1, field2 ) VALUES (value1, value2 )
inserts a new record into the named table
UPDATE table SET field1 = value1, field2 =
value2 WHERE condition changes an existing record or records
DELETE FROM table WHERE condition
removes all records that match condition
SELECT field1, field2 FROM table WHEREcondition
retrieves all records that match condition
8/6/2019 Session 10- JDBC
12/53
JDBC DriversJDBC Drivers
There are four major JDBC Driver Types
y Type I: Bridge - JDBC-ODBC bridge plus ODBC drivery Type II: Native - Native-API partly Java drivery Type III: Middleware - JDBC-Net pure Java drivery Type IV: Pure - Native-protocol pure Java driver
8/6/2019 Session 10- JDBC
13/53
Copyright 1997 AlexChaffee
JDBC DriversJDBC Drivers
JDBC
Type I
Bridge
Type II
Native
Type III
Middleware
Type IV
Pure
ODBCODBC
Driver
CLI (.lib)
Middleware
Server
8/6/2019 Session 10- JDBC
14/53
Copyright 1997Alex Chaffee
TypeI DriversTypeI Drivers
y Uses bridging technology
y Requires
installation/configuration on
client machinesy Not preferable for Web
applications
y Ex. ODBC Bridge
8/6/2019 Session 10- JDBC
15/53
Copyright 1997Alex Chaffee
TypeII DriversTypeII Drivers
y Native API drivers
y Requires
installation/configuration on
client machines
y Usually not thread-safe
y Mostly obsolete now
y Ex. Intersolv Oracle Driver,
WebLogic drivers, OCLI
8/6/2019 Session 10- JDBC
16/53
Copyright 1997Alex Chaffee
TypeIII DriversTypeIII Drivers
y Calls middleware server, usuallyon database host
y Very flexible -- allows access to
multiple databases using one
drivery Only need is to download one
driver
y But requires another server
application to install and maintainy e.g. Symantec DBAnywhere
8/6/2019 Session 10- JDBC
17/53
Copyright 1997Alex Chaffee
TypeIV DriversTypeIV Drivers
y 100% Pure Java
y Uses Java networking libraries to
talk directly to database engines
y
Only disadvantage: need todownload a new driver for each
database engine
y e.g. Oracle, mSQL, AS400
8/6/2019 Session 10- JDBC
18/53
TheStepsof JDBC ApplicationTheStepsof JDBC Application
Here are the steps for a basic JDBC application
Step 1 - Load the driver
Step 2 - Create a database connection
Step 3 - Create a statement Step 4 - Execute the statement(s)
Step 5 - Process the results
Step 6 - Close the resources
8/6/2019 Session 10- JDBC
19/53
Step 1Step 1 -- Loadinga DriverLoadinga Driver
y The Driver(s) must be registered with the DriverManager.
y The most common used method is to manually load it.
import java.sql.*;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
Class.forName(com.oracle.jdbc.OracleDriver").newInstance();
} catch (ClassNotFoundException ex) { ex.printStackTrace(); }
// two drivers now registered with the DriverManager
The driver is supplied by the vendor and must be on the classpath.
The driver class name(s) can be read from a config file (Java properties or
XML) instead of hard coding in the application
An alternate method of loading the driver is via a properties file.
8/6/2019 Session 10- JDBC
20/53
Copyright 1997Alex Chaffee
DriverManagerDriverManager
y DriverManager tries all the drivers
y Uses the first one that works
y When a driver class is first loaded, it registers itself with the DriverManager
y
Therefore, to register a driver, just load it!
Registering a Driver
y We can statically load driver
Class.forName(foo.bar.MyDriver);
Connection c = DriverManager.getConnection(...);
y We can use the jdbc.drivers system property
8/6/2019 Session 10- JDBC
21/53
Copyright 1997Alex Chaffee
JDBC Object ClassesJDBC Object Classes
y DriverManager
Loads, chooses drivers
y Driver
connects to actual database
y Connection
a series ofSQL statements to and from the DB
y Statement
a single SQL statement
y ResultSet
the records returned from a Statement
8/6/2019 Session 10- JDBC
22/53
Copyright 1997Alex Chaffee
JDBC Class UsageJDBC Class Usage
DriverManager
Driver
Connection
Statement
ResultSet
8/6/2019 Session 10- JDBC
23/53
Copyright 1997Alex Chaffee
JDBC URLsJDBC URLsjdbc:subprotocol:source
y
Each driver has its own subprotocoly Each subprotocol has its own syntax for the source
jdbc:odbc:DataSource
e.g. jdbc:odbc:Northwind
jdbc:msql://host[:port]/database
e.g. jdbc:msql://foo.nowhere.com:4333/accounting
FOR AS400 Connectivity :
Class.forName("com.ibm.as400.access.AS400JDBCDriver");
URL = "jdbc:as400://mySystem;naming=sql;errors=full"
Database Default Port is 8471 (9471)
8/6/2019 Session 10- JDBC
24/53
Step 2Step 2 Createa ConnectionCreatea Connection
y Create an instance of a Connection by using the getConnection() fromthe DriverManager.
y The arguments required are: a database URL, userid and password.
import java.sql.*;
static final String url = "jdbc:odbc:ExampleDB_JavaCourse";static final String user = guest";
static final String password = guestpassword";
Connection dbConnection =
DriverManager.getConnection(url, user,password);
y The DriverManager will select the appropriate driver and setup the
DB connection.
y If the DB does not require a user and password then use blanks.
static final String user = "; static final String password = ";
8/6/2019 Session 10- JDBC
25/53
Step 3Step 3 -- CreateastatementCreateastatement
y There are three JDBC statement classes.
Statement-- Basic SQL statements
PreparedStatement- Precompiled SQL for improvedquality
CallableStatement--To execute stored procedures in the
database
Statement class is used to execute basic SQL statements.
8/6/2019 Session 10- JDBC
26/53
Step 3Step 3 -- CreateastatementCreateastatement
import java.sql.*;
static final String url = "jdbc:odbc:ExampleDB_JavaCourse";static final String user = "; static final String password = ";
// Step 1 load the drivertry {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
} catch (ClassNotFoundException ex) { ex.printStackTrace(); }
// Step 2 create a Connection object
Connection dbConnection =DriverManager.getConnection(url, user,password);
// Step 3 create a Statement objecty Statement stmt = dbConnection.createStatement();
8/6/2019 Session 10- JDBC
27/53
Step 4Step 4 -- ExecuteastatementExecuteastatement
Executing a query is an operation frequently performed on
a database so will use this as our example. The result of
executing this query is that a result set containing the
requested information will be returned.
// Step 3 create a Statement object
y Statement stmt = dbConnection.createStatement();
// Step 4 use the Statement object to execute SQL
y Stringquery = select firstname from students;
y ResultSet rs = stmt.executeQuery(query);
8/6/2019 Session 10- JDBC
28/53
Step 5Step 5 -- ProcessingaResultSetProcessingaResultSet
//Step 3 create a Statement objectStatement stmt = dbConnection.createStatement();
//Step 4 use the Statement object to execute SQLStringquery = select FirstName from students;
ResultSet rs = stmt.executeQuery(query);
y // Step 5 process the results row by rowwhile(rs.next() ) {System.out.println(rs.getString(FirstName));}
A result set can be viewed as a table of data containing rows as aresult of a query.
The cursor is initially positioned before the first row. The columns returns are those specified in the query.
8/6/2019 Session 10- JDBC
29/53
Step 6Step 6 -- ClosureClosure
At program termination we would close the objects to ensure thatdatabase resources are released.
Connection dbConnection =DriverManager.getConnection(url,user, password);
Statement stmt = dbConnection.createStatement();Stringquery = select FirstName from students;ResultSet rs = stmt.executeQuery(query);
while(rs.next()) {System.out.println(rs.getString(FirstName));
}
y rs.close();y stmt.close();y dbConnection.close();
8/6/2019 Session 10- JDBC
30/53
SummaryofallthestepsSummaryofallthesteps
The steps for a basic JDBC program
1. Load the driver register with DriverManagerClass.forName("sun.jdbc.odbc.JdbcOdbcDriver").
2. Create a database connection
Connection dbConnection =DriverManager.getConnection(url,user, password);
3. Create a statementStatement stmt = dbConnection.createStatement();
4. Execute the statement(s)stmt.executeQuery(query); stmt.executeUpdate(anUpdate);
5. Process the results
6. Close - rs.close(); stmt.close(); dbConnection.close();
8/6/2019 Session 10- JDBC
31/53
ResultSet & ResultSetMetaDataResultSet & ResultSetMetaData
y Executing an SQL query returns a ResultSet
The ResultSet can be viewed as a table containing the columns specified in the query.
The cursor is initially positioned before first row.
y The result set can be traversed only in the forward direction via the next() method.The result
set can be traversed only once
y ResultSetMetaData= rs.getMetaData()
y Contains all the info aboutTable column count, column labels etc;
y Useful for generic implementation
8/6/2019 Session 10- JDBC
32/53
TraversingaResultSetTraversingaResultSet
Stringquery = select FirstName from students;
ResultSet rs = stmt.executeQuery(query);
y
// Step 5 process the results row by rowwhile(rs.next()) {
System.out.println(rs.getString(FirstName));
}
A result set is a table of data containing rows as a result of a query.
The cursor is initially positioned before the first row.
The columns returns are those specified in the query.
8/6/2019 Session 10- JDBC
33/53
ProcessingaResultSetProcessingaResultSet GettingDataGettingData
The data in the table/result set are SQL data types. When avalue is retrieved it is converted to a Java type.
Individual columns values are read using one of the getXXX()methods. (e.g. getString(), getLong(), getDate(), etc.)
There are two versions of each getXXX() method: one that takes the case-insensitive String name of the
column one that takes an SQL-style column index;(column numbers begin at 1)
y
// Process the results row by rowwhile(rs.next()) {text = rs.getString(1);text = rs.getString(firstname);
}
8/6/2019 Session 10- JDBC
34/53
GettingData GenericallyGettingData Generically
Each getXXX() method will make reasonable type conversions whenthe type of the method does not match the type of the column. Forexample, rs.getString(Price) converts the floating-point value of aPrice column to a string.
The type conversions are performed by the JDBC driver. getObject() is the most generic of the getXXX() methods. getString()is fairly generic
//Price column contains a SQL FLOAT (java.sql.Types.FLOAT)float priceAsPrimitive;String priceAsString;Float priceAsFloat;
while(rs.next()) {priceAsString = rs.getString(Price);priceAsPrimitive = rs.getFloat( Price);priceAsFloat = rs.getObject(Price);
}
8/6/2019 Session 10- JDBC
35/53
Copyright 1997Alex Chaffee
Mapping JavaTypestoSQLTypesMapping JavaTypestoSQLTypes
SQL type Java Type____________
CHAR, VARCHAR, LONGVARCHAR String
NUMERIC, DECIMAL java.math.BigDecimal
BIT boolean
TINYINT byte
SMALLINT short
INTEGER int
BIGINT long
REAL float
FLOAT, DOUBLE double
BINARY, VARBINARY, LONGVARBINARY byte[]
DATE java.sql.Date
TIME java.sql.Time
TIMESTAMP java.sql.Timestamp
8/6/2019 Session 10- JDBC
36/53
JDBCJDBC -- statement.executeUpdate()statement.executeUpdate()
public void actionPerformed(ActionEvent evt) {
String name = theName.getText();
String email = theEmail.getText();
StringSQLupdate = "U
pdate Students Set emailname= '" + email + "' " +
"Where FirstName = '" + name + "'"; // single
quotes
Statement stmt = theConnection.createStatement();int n = stmt.executeUpdate(SQLupdate);
if (n == 0) { System.out.println(No rows updated); }
8/6/2019 Session 10- JDBC
37/53
JDBCJDBC -- PreparedStatementPreparedStatement
y There are three JDBC statement classes.
Statement
Basic SQL statements
PreparedStatement
Precompiled SQL for improved performance
CallableStatement
To execute stored procedures in the database
8/6/2019 Session 10- JDBC
38/53
JDBCJDBC -- PreparedStatementPreparedStatement
When the database engine executes a SQL query viaexecuteQuery() it must process the SQL statement.Processing includes parsing and optimizing the SQLstatement.
Parsing checking syntax, are the objects (table names,etc) in the DB, are the data conversion legal
Optimizing finding the best access path
If the SQL statement is used frequently then doing theoverhead processing in advance (preparing) canimprove performance.
(approx. 2 to 10 times faster depending on the complexityof the SQL statement, number of iterations, etc.)
8/6/2019 Session 10- JDBC
39/53
JDBCJDBC -- PreparedStatementPreparedStatement
The Connection object performs the parsing/preparation.
The PreparedStatement has place-holders for the parameters that willbe used when the statement is executed.
The values for the parameters are set using one of the setXXX()methods.
y Assume we have a table to keep track of student assignments.Thevalue of an assignment is a grade. We want to get the value of allassignments for a given student.
Stringquery1 = select assgn1, assgn2, assgn3 from
studentAssignments where firstname = ? and lastname = ?;
PreparedStatement ps1 = conn.prepareStatement(query1);ps1.setString(1, John); ps1.setString(2, Doe);ResultSet rs = ps1.executeQuery();
8/6/2019 Session 10- JDBC
40/53
CallableStatement ExampleCallableStatement Example
String createProcedure = "create procedure SHOW_STUDENTS +
as select NAME from STUDENTS order by NAME;";
y Statement stmt = con.createStatement();
y stmt.executeUpdate(createProcedure);
y CallableStatement cs = con.prepareCall("{call SHOW_STUDENTS}");
y ResultSet rs = cs.executeQuery();
Syntax for creating procedures differs on different DBMS
Different DBMS support creation of different procedures
8/6/2019 Session 10- JDBC
41/53
CallablestatementsCallablestatements
CallableStatement is a subclass of PreparedStatement
y It can take input parameters
String callProcedure = {call insertUsers(?)};
CallableStatement cs = con.prepareCall(callProcedure);
cs.setString(1, T
om Cruise");cs.execute();
y It can also return output parameters
String callProcedure = {call isValidUser (?,?)};
CallableStatement cs = con.prepareCall(callProcedure );
cs.setString(1, Tom Cruise");
cs.registerOutParameter(2, java.sql.Types.integer);
cs.execute();
integer i = cs.getInteger(2);
8/6/2019 Session 10- JDBC
42/53
SummaryofStatementsSummaryofStatements
y Statement
For simple SQL statements (no parameters)
Good for statements that are run once
y
PreparedStatement For SQL statements with one or more inputparameters
Good for simple SQL statements that are executedfrequently
y CallableStatement For executingSQL stored procedures
Last longer than program itself
8/6/2019 Session 10- JDBC
43/53
Copyright 1997Alex Chaffee
OptimizedStatementsOptimizedStatements
y Prepared Statements
SQL calls you make again and again
allows driver to optimize (compile) queries
created with Connection.prepareStatement()
y Stored Procedures
written in DB-specific language
stored inside database
accesed with Connection.prepareCall()
8/6/2019 Session 10- JDBC
44/53
Copyright 1997Alex Chaffee
TransactionsTransactions
y Transaction = more than one statement whichmust all succeed (or all fail) together
y If one fails, the system must reverse all previousactions
y Also cant leave DB in inconsistent state halfwaythrough a transaction
COMMIT = complete transaction
ROLLBACK = abort
8/6/2019 Session 10- JDBC
45/53
JDBCJDBC --TransactionsTransactions
There are situations in which we must treat a number of
DB operations (queries, updates) as an atomic action.
Either All or None
y Must update more than one table. If one update fails then
want to back out change changes that have already been
posted.
y Two users/threads may be operating on the same set of
data. Similar to synchronizing threads, create an atomic
action.
y These atomic actions are achieved by usingTransactions.
8/6/2019 Session 10- JDBC
46/53
Copyright 1997Alex Chaffee
TransactionManagementTransactionManagement
y Transactions are not explicitly opened and closedy Instead, the connection has a state called AutoCommit
modey IfAutoCommitis true, then every statement is
automatically committedy Default case: true
Connection.setAutoCommit(boolean)y IfAutoCommitis false, then every statement is
added to an ongoing transactionyWe must explicitly commit or rollback thetransaction using Connection.commit() andConnection.rollback()
8/6/2019 Session 10- JDBC
47/53
TransactionTransaction ISOLATIONISOLATION
y READ UNCOMMITTED
When it's used, DBMS will not issue shared locks while reading data.
This isolation level is also called dirty read.This is the lowest isolation
level.
y READ COMMITTED
This is the default isolation level in DBMS. DBMS will use shared
locks while reading data. It ensures that it will never read data thatanother application has changed and not yet committed. It does not
ensure that the data will not be changed before the end of the
transaction.
8/6/2019 Session 10- JDBC
48/53
y REPEATABLE READ
When it's used, then dirty reads and nonrepeatable reads
cannot occur. It means that locks will be placed on all data
that is used in a query, and another transactions cannot
update the data.
y SERIALIZABLE
Most restrictive isolation level. When it's used, then
phantom values cannot occur. It prevents other users from
updating or inserting rows into the data set until the
transaction is complete.
TransactionTransaction ISOLATIONISOLATION
8/6/2019 Session 10- JDBC
49/53
JDBCJDBC --TransactionsTransactions
y
A transactions consists of a group of operations.
The transactions is only permanently posted to the database if it iscommitted. If the program terminates abnormally the transaction isautomaticallyrolled back. By default each JDBC operations occur in a transaction that isautomatically committed.
try {conn.setAutoCommit(false);// default commits each operationstmt.executeQuery(aQuery);stmt.executeUpdate(updateOne);
stmt.executeQuery(updateTwo);conn.commit(); // Commit the transaction}catch(SQLException se) {
conn.rollback(); // back out changes temporarily posted}
8/6/2019 Session 10- JDBC
50/53
Copyright 1997Alex Chaffee
JDBC Class DiagramJDBC Class Diagram
8/6/2019 Session 10- JDBC
51/53
Copyright 1997Alex Chaffee
ResourcesResources
y Reese, Database Programming with JDBC and Java(OReilly)
y http://java.sun.com/products/jdbc/
y http://java.sun.com/products/java-blend/
y
http://www.purpletech.com/java/y List of Available JDBC Drivers
http://industry.java.sun.com/products/jdbc/drivers/
y API for java.sql
http://java.sun.com/j2se/1.4/docs/api/java/sql/packa
ge-summary.html
8/6/2019 Session 10- JDBC
52/53
Questions ???
8/6/2019 Session 10- JDBC
53/53
ThankYou