Transcript ppt

JDBC – Java Database
Concentricity
Representation and Management of
Data on the Internet
Relational Databases
• Data stored in records (tuples) which live in
tables (relations)
• Maps row (record) to column (field) in a
single table
A
1
B
2
C
3
D
4
4
3
2
1
A (very short) Reminder of SQL
• Creating tables:
CREATE TABLE books (
isbn INTEGER primary key,
title VARCHAR2(40) not null,
abstract TEXT);
A (very short) Reminder of SQL
• Inserting tuples into the tables
INSERT INTO books(isbn, title)
VALUES (12345, “Foundations
of Database”)
A (very short) Reminder of SQL
• Updating tuples in the tables
UPDATE books SET
title=“Foundation of Databases”
WHERE isbn=12345;
A (very short) Reminder of SQL
• Deleting tuples from the tables
DELETE FROM books
WHERE title like ‘%goblin%;
A (very short) Reminder of SQL
• Queries
SELECT title
FROM books
WHERE abstract like ‘%hobbit%;
Transactions
• Transaction = more than one statement
which must all succeed (or all fail) together
• If one fails, the system must reverse all
previous actions
• Also can’t leave DB in inconsistent state
halfway through a transaction
• COMMIT = complete transaction
• ROLLBACK = abort
Working With Oracle
Add to your .cshrc the following:
if ($HOST == sol4) then
setenv ORACLE_HOME /opt/oracle
else
setenv ORACLE_HOME /usr/local/oracle8i
endif
setenv PATH $ORACLE_HOME/bin:$PATH
setenv ORACLE_SID stud
Calling Oracle
• If a student whose login is Snoopy wants to
work directly with Oracle:
sqlplus snoopy/[email protected]
• Note: we use the login for a password!
Introduction to JDBC
• JDBC is used for accessing databases from
Java applications
• Information is transferred from relations to
objects and vice-versa
– databases optimized for searching/indexing
– objects optimized for engineering/flexibility
Overview
RMI
JDBC
java.net
TCP/IP
Network OS
CORBA
JDBC Drivers (Fig.)
Type I
“Bridge”
JDBC
Type II
“Native”
Type III
“Middleware”
Type IV
“Pure”
ODBC
ODBC
Driver
CLI (.lib)
Middleware
Server
Java Package
JDBC is implemented in
Java in the package
java.sql
Seven Steps
•
•
•
•
•
•
•
Load the driver
Define the Connection URL
Establish the Connection
Create a Statement object
Execute a query
Process the result
Close the connection
Important Classes
• DriverManager
– loads, chooses drivers
• Driver
– connects to actual database
• Connection
– a series of SQL statements to and from the DB
• Statement
– a single SQL statement
• ResultSet
– the records returned from a Statement
DriverManager
Driver
Connection
Statement
ResultSet
Loading the Driver
• Registering the Driver directly
automatically:
Class.forName(
“oracle.jdbc.driver.OracleDriver");
• Calling Class.forName, automatically
– creates an instance of the driver
– registers the driver with the DriverManager
Another Option
• Another option is to create an instance of
the driver and register it with the Driver
Manager:
Driver driver = new
oracle.jdbc.OracleDriver();
DriverManager.registerDriver(driver);
The DriverManager
• The DriverManager tries all the drivers
• Uses the first one that works
• When a driver class is first loaded, it
registers itself with the DriverManager
• Therefore, to load a driver, just register it!
Creating a Connection
• Use getConnection on the Driver
Connection getConnection
(String url,
String user,
String password)
• Connects to given JDBC URL with given user
name and password
• Throws java.sql.SQLException
• returns a Connection object
URLS
• Gives the required information for making
the connection to the database
• For example, Snoopy will use the URL
jdbc:oracle:thin:snoopy/snoopy@sol4:152
1:stud
Password
Path to driver
Database name
User name
Host
Port
Connection
• A Connection represents a session with a
specific database
• Within the context of a Connection, SQL
statements are executed and results are
returned
Connections
• There can be multiple connections to a
database
• A connection provides “metadata”, i.e.,
information about the database, tables, and
fields
• Connection object has methods to deal with
transactions
Creating a Connection
String url
=
"jdbc:oracle:thin:snoopyo/snoopy@sol4:1521:stud";
try {
Class.forName (“oracle.jdbc.OracleDriver");
Connection con =
DriverManager.getConnection(url);
}
catch (ClassNotFoundException e)
{ e.printStackTrace(); }
catch (SQLException e)
{ e.printStackTrace(); }
Statements
Statement createStatement()
– returns a new Statement object
PreparedStatement
prepareStatement(String sql)
– returns a new PreparedStatement object
CallableStatement
prepareCall(String sql)
– returns a new CallableStatement object
• Why all these different kinds of statements?
Statements
• A Statement object is used for executing a
static SQL statement and obtaining the
results produced by it
• executeQuery is used for statements that
return an output result
• executeUpdate is used for statements that
need not return an output
Executing Queries and Updates
ResultSet executeQuery(String)
– Execute a SQL statement that returns a single
ResultSet
int executeUpdate(String)
– Execute a SQL INSERT, UPDATE or DELETE
statement
– Used for CREATE TABLE, DROP TABLE and
ALTER TABLE
– Returns the number of rows changed
Timeout
• Use setQueryTimeOut to set a timeout for
the driver to wait for a statement to be
completed
• If the operation is not completed in the
given time, an SQLException is thrown
• What is it good for?
Cursor
• What is the result of a query?
• Is a remote connection different from a
direct access to the database?
• How can a database send the result of a
query through communication lines?
• The answer: using a cursor
Result Set
• A ResultSet provides access to a table of data
generated by executing a Statement
• Only one ResultSet per Statement can be open at
once
• The table rows are retrieved in sequence
• A ResultSet maintains a cursor pointing to its
current row of data
• The 'next' method moves the cursor to the next
row
– you can’t rewind
Working with ResultSet
• boolean next()
– activates the next row
– the first call to next() activates the first row
– returns false if there are no more rows
• void close()
– disposes of the ResultSet
– allows you to re-use the Statement that created it
– automatically called by most Statement methods
Getting Values from Rows
• Type getString(int
columnIndex)
getType
– returns the given field as the given type
– fields indexed starting at 1 (not 0)
• Type getString(String
columnName)
getType
– same, but uses name of field
– less efficient
• int findColumn(String columnName)
– looks up column index given column name
Example
Code Example
Optimized Statements
• Prepared Statements
– SQL calls that you make again and again
– allows driver to optimize (compile) queries
– created with Connection.prepareStatement()
• Stored Procedures
– written in DB-specific language
– stored inside database
– accesed with Connection.prepareCall()
Metadata
• Connection:
– DatabaseMetaData getMetaData()
• ResultSet:
– ResultSetMetaData getMetaData()
Useful Methods of Metadata
•
•
•
•
•
getColumnCount
getColumnDisplaySize
getColumnName
getColumnType
isNullabale
Imagine the case where you want to print
the result
Transaction Management
• Transactions are not explicitly opened and
closed
• Instead, the connection has a state called
AutoCommit mode
• if AutoCommit is true, then every statement
is automatically committed
• default case: true
AutoCommit
Connection.setAutoCommit(boolean)
• if AutoCommit is false, then every statement
is added to an ongoing transaction
• you must explicitly commit or rollback the
transaction using Connection.commit() and
Connection.rollback()
Connection Manager
• For a large threaded database server, create a
Connection Manager object
• It is responsible for maintaining a certain number
of open connections to the database
• When your applications need a connection, they
ask for one from the CM’s pool
• Why? Because opening and closing connections
takes a long time
• Warning: the CM should always
setAutoCommit(false) when a connection is
returned