Instead of accessing the database directly, we can access it via a Data Source Name DSN... Click Add and select the Microsoft Access Driver *.mdb Click Add and select the Microsoft Acce
Trang 1CHAPTER 4
DATABASE
CONNECTIVITY
Trang 5What Is JDBC? (cont.)
Portability is one of the key aspects of JDBC
Can you imagine using Java for writing an application once and executing it on a large number of platforms—and then having to
5
number of platforms—and then having to
change the code when your organization
switches from Microsoft SQL Server to
Trang 7What Is JDBC? (cont.)
7
Application programmers use the JDBC API
Database vendors and tool providers use the JDBC Driver API
This architecture follows the successful model
This architecture follows the successful model
of Microsoft’s ODBC, which provided a C
programming interface for database access
Trang 9JDBC vs ODBC
9
Why not just use ODBC from Java?
Answer: You can use ODBC from Java, but
with the help of JDBC in the form of the ODBC Bridge
JDBC-ODBC Bridge
The question now becomes, "Why do you
need JDBC?"
Trang 10JDBC vs ODBC (cont.)
10
There are several reasons to this question:
ODBC is hard to learn It mixes simple and advanced features together, and it has complex options even for simple queries.
ODBC is not appropriate for direct use from Java
because it uses a C interface Calls from Java to native C code have a number of drawbacks in the security, implementation, robustness, and
automatic portability of applications.
Trang 11JDBC vs ODBC (cont.)
11
There are several reasons to this question:
ODBC relies on the use of void* pointers and other C features that are not natural in Java.
An ODBC-based solution is inherently less safe and harder to deploy than a pure Java solution.
Trang 12Typical Uses of JDBC
12
The JDBC API supports both two-tier and
three-tier models for database access
In the two-tier model, a Java applet or
application talks directly to the database This
application talks directly to the database This requires a JDBC driver deployed on the client
Figure 1: Two-tier Architecture for Data Access.
Trang 13Typical Uses of JDBC (cont.)
13
A user's commands are delivered to the
database, and the results of those statements are sent back to the user
The data source may be located on another
The data source may be located on another machine to which the user is connected via a network
This is client/server model, with the user's
machine as the client, and the machine
housing the data source as the server
Trang 14Typical Uses of JDBC (cont.)
14
Java applet or HTML browser Client machine (GUI)
HTTP, RMI, CORBA, or other calls
Figure Three-tier Architecture for Data Access.
Application Server
(Java)
JDBC
Server machine (business logic) HTTP, RMI, CORBA, or other calls
DBMS-proprietary protocol
Trang 16The Structured Query Language
16
A database: a bunch of named tables with
rows and columns Each column has a column name The rows contain the actual data or
records
The Authors Table
Author_ID Name Fname
Trang 18driver to access data.
Instead of accessing the database directly, we can access it via a Data Source Name (DSN)
Trang 19JDBC Installation (cont.)
19
Set up a DSN and get a connection through that:
Choose Control Panel > Administrative Tools > Data Sources.
In the ODBC Data Source Administrator dialog box, click the System DSN tab.
Click Add and select the Microsoft Access Driver (*.mdb)
Click Add and select the Microsoft Access Driver (*.mdb)
Type in the name mdbTEST for the Data Source Name
Click Create and select a file to save the database to (I chose "d:\java\mdbTEST.mdb") - this creates a new blank
MS Access database!
Click “OK" all the way out
Trang 21Database URLs
21
All classes used for JDBC programming are
contained in the java.sql and javax.sql
packages.
Database URLs:
jdbc:subprotocol : other stuff
jdbc:subprotocol : other stuff
subprotocol selects the specific driver for connecting
Trang 22Making the Connection
22
To set up our DriverManager and let it know that we want to communicate with ODBC data sources via the JDBC:ODBC bridge, we call the forName() method of the Class class
Trang 23Connect to MS SQL Server 2000 & MySQL
23
MS SQL Server 2000
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver" );
String dburl = "jdbc:sqlserver://localhost:1433;" +
Trang 24Executing SQL Commands
24
Firstly, create a Statement object To do that, use the Connection object that you obtained from the call to
String command = “UPDATE Books”
+ “ SET Price = Price – 5.00”
+ “ WHERE Title NOT LIKE
‘%Introduction%’”;
Trang 25Executing SQL Commands (cont.)
25
Then call the executeUpdate method:
stat.executeUpdate(command);
This method returns a count of the rows
affected by the SQL command
The executeUpdate method can execute actions such as:
INSERT , UPDATE , and DELETE
Data definition commands: CREATE TABLE ,
Trang 26Executing SQL Commands (cont.)
* FROM Books”);
while (rs.next())
look at a row of the result set
}
There is also a catch-all execute statement to
execute arbitrary SQL statements.
Trang 27Executing SQL Commands (cont.)
27
To know the contents of the fields:
String isbn = rs.getString(1);
double price = rs.getDouble(“Price”);
There are accessors for various types:
getString, getDouble,…
getString, getDouble,…
Each accessor has two form: one with a
numeric argument (column number), one with
a string argument (column name).
Unlike array indexes, database column
numbers start at 1
Trang 28Executing SQL Commands (cont.)
28
SQL data types and Java data types are not exactly the same See the below table
SQL Data Type Java Data Type
Trang 29Executing SQL Commands (cont.)
29
SQL Data Type Java Data Type
CHARACTER(n) or CHAR(n) String
Trang 30Data Types in MS Access
30
Trang 31Advanced SQL Types
31
Many databases can store large objects such as
images or other data.
Binary large objects: BLOBs.
Character large objects: CLOBs.
The getBlob and getClob methods return
The getBlob and getClob methods return
objects of type java.sql.Blob and
java.sql.Clob
A SQL ARRAY is a sequence of values.
Ex: In a Student table, you can have a Scores
column that is an ARRAY OF INTEGER
Trang 32Managing Connections, Statements, and Result Sets
32
Every Connection object can create one or
more Statement objects
You can use the same Statement object for
Trang 33Managing Connections, Statements, and Result Sets (cont.)
Call the close method on Statement object:
Call the close method on Statement object:
closes this statement object and its associated result set.
These objects use large data structures, and
you don’t want to wait for the garbage collector
to deal with them
Trang 34Managing Connections, Statements, and Result Sets (cont.)
to deal with exceptions
Trang 38Example 1 (cont.)
38
Trang 39“Any”.
Click the Query
button; all books
matching your
selection will be
displayed in the text area.
Trang 40Click the button,
Click the button,
all prices of that
publisher are
adjusted by the
amount you
entered
Trang 41publisher, independent of the author:
SELECT Books.Price, Books.Title
FROM Books, Publishers
WHERE Books.Publisher_Id = Publishers.Publisher_Id AND Publishers.Name = the name from the list box
Trang 42Prepared Statements (cont.)
42
Instead of using a separate query statement every time the user launches such a query, we
can prepare a query with a host variable.
Each host variable is indicated with a ?
Each host variable is indicated with a ?
String publisherQuery =
“SELECT Books.Price, Books.Title” +
“ FROM Books, Publishers” +
“ WHERE Books.Publisher_Id = Publishers.Publisher_Id AND Publishers.Name = ?”;
Trang 43Prepared Statements (cont.)
Once all variables have been set to values,
you can execute the query:
publisherQueryStat. setString(1, publisher);
// The position 1 denotes the first ?
// The second argument is the value that we want
to assign to the host variable
ResultSet rs = publisherQueryStat executeQuery() ;
Trang 44Prepared Statements (cont.)
44
The price update feature is implemented as an
UPDATE statement
UPDATE Books
SET Price = Price + ?
WHERE Books.Publisher_Id = (SELECT Publisher_Id
We call executeUpdate, not executeQuery The return value of executeUpdate is the
count of changed rows
WHERE Books.Publisher_Id = (SELECT Publisher_Id
FROM Publishers WHERE Name = ?)
Trang 45Summary of Necessary APIs
To execute a query void setXxx(int n ,
Xxx x ) Xxx x ) ResultSet
executeQuery(String
sql )
ResultSet executeQuery()
int executeUpdate(String
sql )
int executeUpdate()
boolean execute(String sql )
boolean execute()
Trang 46Summary of Necessary APIs
one Returns false after the last row.
•Xxx getXxx( int columnNumber)
•Xxx getXxx (String columnName)
(Xxx is a type such as int, double, String, Date, etc.) return the value of the column with the given column number or name, converted to the specified type Not all type conversions are legal.
Note: The column number belongs to the column in the result set, not the one in the database.
Trang 48Scrollable Result Sets
48
Suppose that you want to move backward in the result set But JDBC 1 had no previous
method
Since JDBC 2.0 API (JavaTM 2 SDK, Standard
Since JDBC 2.0 API (Java 2 SDK, Standard Edition, version 1.2), you can move forward and backward and jump to any position in the result set
Trang 49Scrollable Result Sets (cont.)
49
To obtain scrollable result sets from your
queries, you must use:
Statement stat = conn createStatement (type,
Trang 50Scrollable Result Sets (cont.)
50
You have the following choices:
Do you want the result set to be scrollable or not?
If not, use ResultSet.TYPE_FORWARD_ONLY
If the result set is scrollable, do you want it to be able to reflect changes in the database occurred after the query that yielded it?
Do you want to be able to update the database by editing the result set?
Trang 51Scrollable Result Sets (cont.)
51
ResultSet Type Values
TYPE_FORWARD_ONLY The result set is not scrollable.
TYPE_SCROLL_INSENSITIVE The result set is scrollable but not
sensitive to database changes.
TYPE_SCROLL_SENSITIVE The result set is scrollable and
ResultSet Concurrency Values
TYPE_SCROLL_SENSITIVE The result set is scrollable and
sensitive to database changes.
CONCUR_READ_ONLY The result set cannot be used to
update the database.
CONCUR_UPDATABLE The result set can be used to
update the database.
Trang 52Scrollable Result Sets (cont.)
ResultSet rs = stat.executeQuery( query );
Trang 53Scrollable Result Sets (cont.)
Trang 54Scrollable Result Sets (cont.)
the 1 row.
To move backward or forward by a number of rows:
rs.relative(n);
If n > 0, the cursor moves forward.
If n < 0, the cursor moves backward.
Trang 55Scrollable Result Sets (cont.)
55
To set the cursor to a particular row number:
rs.absolute(n);
To get the current row number:
int currentRow = rs.getRow();
int currentRow = rs.getRow();
1 st row in the result set has number 1
If the return value is 0, the cursor is not on a row
It is either before the first row or after the last row.
Trang 56Scrollable Result Sets (cont.)
Using a scrollable result set is very simple
The hard work of caching the query data is
carried out by the database driver
Trang 57Updatable Result Sets
57
Using this mechanism, you can edit result set
and the changes are automatically reflected in the database
To obtain updatable result sets:
The result sets returned by a call to
executeQuery are then updatable
Statement stat =
conn.createStatement(ResultSet.TYPE_SCROLL_INSENSI
TIVE, ResultSet.CONCUR_UPDATABLE );
Trang 58Updatable Result Sets (cont.)
double price = rs.getDouble("Price");
rs.updateDouble ("Price", price + increase);
rs.updateRow ();
} }
Trang 59Updatable Result Sets (cont.)
59
java.sql.ResultSet:
Xxx data )
(Xxx is a type such as int , double , String ,
Date , etc.) update a field in the current row of the
Trang 60Updatable Result Sets (cont.)
60
To make the updates effective:
void updateRow() Sends all updates in the current row to the database.
To cancel the updates to the current row:
void cancelRowUpdates() Call this method after calling an updater method(s) and before calling the
method updateRow to roll back the updates
Trang 61Updatable Result Sets (cont.)
Build up a new row
Move the cursor to a special position,
called the insert row.
Deliver the new row to the database
Trang 62Updatable Result Sets (cont.)
62
To delete the row:
void deleteRow() Removes the row from both the result set and the database.
give you the same power as executing
commands
Trang 6464
In SQL, data that describe the database or one
of its parts are called metadata
You can get three kinds of metadata: about a database, about a result set, and about
parameters of prepared statements
parameters of prepared statements
To get metadata of a database:
DatabaseMetaData meta = conn.getMetaData();
ResultSet mrs = meta.getTables(null, null, null, new String[] { “TABLE” });
return a result set that contains information about
Trang 65column’s name, type, and field width.
String query = "SELECT * FROM Books";
ResultSet rs = stat.executeQuery(query);
ResultSetMetaData meta = rs.getMetaData ();
for (int i = 1; i <= meta.getColumnCount (); i++) {
String columnName = meta.getColumnLabel (i);
int columnWidth = meta.getColumnDisplaySize (i);
Trang 6868
A set of statements can be grouped to form a
transaction
The transaction can be committed when all
has gone well Or, if an error has occurred in has gone well Or, if an error has occurred in
one of them, it can be rolled back.
Trang 69Transactions (cont.)
69
Main reason for grouping commands into
transactions is database integrity
Example: Suppose we want to transfer money
from one bank account to another
from one bank account to another
Simultaneously debit one account and credit another.
If the system fails before crediting the other
account, the debit needs to be undone.
Trang 70Transactions (cont.)
70
By default, a database connection is in
autocommit mode
This means that each SQL command is
committed to the database as soon as it is
committed to the database as soon as it is
executed and you cannot roll it back.
To check the current autocommit mode setting:
To turn off autocommit mode:
Trang 71Transactions (cont.)
71
Now you create a statement object:
Call executeUpdate any number of times:
Trang 72Save Points
72
You can gain more control over the rollback
process by using save points
Creating a save point marks the place where you can later return without having to return to you can later return without having to return to the start of the transaction
Trang 73Save Points (cont.)
73
Example:
Statement stat = conn.createStatement(); // start
transaction; rollback() goes here
stat.executeUpdate(command1);
stat.executeUpdate(command1);
Savepoint svpt = conn.setSavepoint(); // set
savepoint; rollback(svpt) goes here
Trang 74The commands in a batch can be:
INSERT , UPDATE , and DELETE
CREATE TABLE and DROP TABLE
Trang 75Batch Updates (cont.)
75
To execute a batch:
Statement stat = conn.createStatement();
// Instead of calling executeUpdate, call addBatch
String command = “CREATE TABLE ”;
stat.addBatch(command);
Finally, you submit the entire batch:
int[] counts = stat.executeBatch();
while ( ) {
command = “INSERT INTO VALUES (” + … + “)”; stat.addBatch(command);
}