Download presentation
Presentation is loading. Please wait.
1
JDBC – Java Database Concentricity
Representation and Management of Data on the Internet
2
Relational Databases Data stored in records (tuples) which live in tables (relations) Maps row (record) to column (field) in a single table A B C D 1 2 3 4 4 3 2 1
3
A (very short) Reminder of SQL
Creating tables: CREATE TABLE books ( isbn INTEGER primary key, title VARCHAR2(40) not null, abstract TEXT);
4
A (very short) Reminder of SQL
Inserting tuples into the tables INSERT INTO books(isbn, title) VALUES (12345, “Foundations of Database”)
5
A (very short) Reminder of SQL
Updating tuples in the tables UPDATE books SET title=“Foundation of Databases” WHERE isbn=12345;
6
A (very short) Reminder of SQL
Deleting tuples from the tables DELETE FROM books WHERE title like ‘%goblin%;
7
A (very short) Reminder of SQL
Queries SELECT title FROM books WHERE abstract like ‘%hobbit%;
8
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
9
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
10
sqlplus snoopy/snoopy@stud.cs
Calling Oracle If a student whose login is Snoopy wants to work directly with Oracle: sqlplus Note: we use the login for a password!
11
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
12
Overview RMI JDBC CORBA java.net TCP/IP Network OS
13
JDBC Drivers (Fig.) JDBC Type I “Bridge” ODBC ODBC Driver Type II
“Native” CLI (.lib) Type III “Middleware” Middleware Server Type IV “Pure”
14
Java Package JDBC is implemented in Java in the package java.sql
15
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
16
Important Classes DriverManager Driver Connection Statement ResultSet
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
17
DriverManager Driver Connection Statement ResultSet
18
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
19
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);
20
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!
21
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
22
URLS Gives the required information for making the connection to the database For example, Snoopy will use the URL Path to driver User name Password Port Host Database name
23
Connection A Connection represents a session with a specific database
Within the context of a Connection, SQL statements are executed and results are returned
24
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
25
Creating a Connection String url = try { Class.forName (“oracle.jdbc.OracleDriver"); Connection con = DriverManager.getConnection(url); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e)
26
Statements Why all these different kinds of 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?
27
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
28
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
29
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?
30
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
31
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
32
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
33
Getting Values from Rows
Type getString(int columnIndex) returns the given field as the given type fields indexed starting at 1 (not 0) Type getString(String columnName) same, but uses name of field less efficient int findColumn(String columnName) looks up column index given column name getType
34
Example Code Example
36
Optimized Statements Prepared Statements Stored Procedures
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()
37
Metadata Connection: ResultSet: DatabaseMetaData getMetaData()
ResultSetMetaData getMetaData()
38
Useful Methods of Metadata
getColumnCount getColumnDisplaySize getColumnName getColumnType isNullabale Imagine the case where you want to print the result
39
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
40
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()
41
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
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.