You are on page 1of 24

JDBC –

Java DataBase Connectivity
CSE432 Object Oriented Software Engineering

What is JDBC?

“An API that lets you access virtually any tabular data source from the Java programming language”

JDBC Data Access API – JDBC Technology Homepage

What’s an API?  See J2SE documentation  What’s a tabular data source? “… access virtually any data source, from relational databases to spreadsheets and flat files.”

JDBC Documentation

We’ll focus on accessing Oracle databases
2

General Architecture    What design pattern is implied in this architecture? What does it buy for us? Why is this architecture also multi-tiered? 3 .

4 .

Establish a connection 2.Create JDBC Statements 3.Close connections 5 .Basic steps to use a database in Java      1.GET ResultSet 5.Execute SQL Statements 4.

driver.1. username. for Oracle database  Make the connection  Connection con = DriverManager. Load the vendor specific driver  Class.   What do you think this statement does? Establishes connection to database by obtaining a Connection object 6 . passwd).forName("oracle. Establish a connection   import java.sql.getConnection( "jdbc:oracle:thin:@oracle-prod:1521:OPROD". and how? Dynamically loads a driver class.OracleDriver").   What do you think this statement does.jdbc.*.

Creates a Statement object for sending SQL statements to the database 7 .createStatement() . Create JDBC statement(s)   Statement stmt = con.2.

8  . //What does this statement do? String insertLehigh = "Insert into Lehigh values“ + "(123456789.executeUpdate(insertLehigh).executeUpdate(createLehigh).100)".abc. stmt. " + "Marks Integer)". Name VARCHAR(32). stmt.Executing SQL Statements  String createLehigh = "Create table Lehigh " + "(SSN Integer not null.

//What does this statement do? while (rs.executeQuery(queryLehigh). int marks = rs. String name = rs.getInt("SSN").getString("NAME").next()) { int ssn = rs. ResultSet rs = Stmt.Get ResultSet String queryLehigh = "select * from Lehigh".getInt("MARKS"). } 9 .

close(). con. 10 .Close connection   stmt.close().

e. no SQL statement will be committed until an explicit is invoked con. At this point all changes done by the SQL statements will be made permanent in the database.Transactions and JDBC       JDBC allows SQL statements to be grouped together into a single transaction Transaction control is performed by the Connection object. Once auto-commit is off.commit().setAutoCommit(true). And turn it back on with con. I.setAutoCommit(false). default mode is auto-commit. each sql statement is treated as a transaction We can turn off the auto-commit mode with con.. 11 .

If a statement in the try block throws an exception or warning. it can be caught in one of the corresponding catch statements How might a finally {…} block be helpful here? E. you could rollback your transaction in a catch { …} block or close database connection and free database related resources in finally {…} block 12 .g.Handling Errors with Exceptions     Programs should recover and leave the database in a consistent state..

Another way to access database (JDBC-ODBC) What’s a bit different about this architecture? Why add yet another layer? 13 .

getConnection( database .mdb)}. //dynamic loading of driver String filename = "c:/db1.mdb". s. //add on to end Connection con = DriverManager. s. //Location of an Access database String database = "jdbc:odbc:Driver={Microsoft Access Driver (*.odbc. class Test { public static void main(String[] args) { try { Class.createStatement(). Statement s = con.""). 14 .sql. s.*. database+= filename.jdbc.execute("select firstcolumn from TEST12345").execute("create table TEST12345 ( firstcolumn integer )").Sample program import java.READONLY=true}".execute("insert into TEST12345 values(1)").forName("sun.DBQ=".trim() + ".DriverID=22."".JdbcOdbcDriver").

// close Statement to let the database know we're done with it con. if (rs != null) // if rs == null. } s.println("Data from column_name: " + rs.getResultSet().out.next() ) // this will step through our data row-by-row { /* the next line will get the first column in our current row's ResultSet as a String ( getString( columnNumber) ) and output it to the screen */ System. then there is no ResultSet to view while ( rs.Sample program(cont) ResultSet rs = s.println("ERROR: " + err).getString(1) ).close(). } } } 15 . //close connection } catch (Exception err) { System.close().out.

Mapping types JDBC .Java 16 .

absolute(100).previous(). / / go 7 records forward rs.JDBC 2 – Scrollable Result Set … Statement stmt = con.TYPE_SCROLL_INSENSITIVE.executeQuery( query ).relative(7). ResultSet rs = stmt. / / go 5 records back rs.CONCUR_READ_ONLY). rs. String query = “select students from class where type=„not sleeping‟ “. / / go to 100th record … 17 . / / go back in the RS (not possible in JDBC 1…) rs.createStatement(ResultSet. ResultSet.relative(-5).

updateRow().JDBC 2 – Updateable ResultSet … Statement stmt = con.createStatement(ResultSet. ResultSet rs = stmt. rs. grade+10). String query = " select students. … while ( rs.updateInt(“grade”.executeQuery( query ). rs.TYPE_FORWARD_ONLY. } 18 .CONCUR_UPDATABLE). ResultSet. grade from class where type=„really listening this presentation‟ “.next() ) { int grade = rs.getInt(“grade”).

19 .Metadata from DB  A Connection's database is able to provide schema information describing its tables. its stored procedures the capabilities of this connection. and so on   What is a stored procedure? Group of SQL statements that form a logical unit and perform a particular task This information is made available through a DatabaseMetaData object. its supported SQL grammar.

Metadata from DB . String catalog = null. .getTables(catalog . schema . … 20 . String table = “sys%”. String[ ] types = null.example … Connection con = …. types ). DatabaseMetaData dbmd = con. table .getMetaData(). ResultSet rs = dbmd. String schema = null.

"). ++i) System.getColumnCount()."). System.getString( i)+".out.getColumnName( i)+". } } 21 . i < nCols.println( rs.out.print( rs. // print column names for(int i=1.print( md. / / output resultset while ( rs. // get number of columns int nCols = md.out.next() ) { for(int i=1.getMetaData(). ++i) System.JDBC – Metadata from RS public static void printRS(ResultSet rs) throws SQLException { ResultSetMetaData md = rs.getString(nCols) ). i < nCols.

load objects from RDBMS Standardized and optimized by Sybase. using RDBMS as repository Save. machines. services. Oracle and IBM Java extended with directives: # sql SQL routines can invoke Java methods Maps SQL types to Java classes 22  (JDO) Java Data Object    (SQLJ) Embedded SQL in Java     . networks.JDBC and beyond  (JNDI) Java Naming and Directory Interface   API for network-wide sharing of information about users. and applications Preserves Java’s object model Models persistence of objects.

4.sun.html http://java.com/j2se/1.2/docs/guide/jdbc/index.sun.html http://java.html http://java.JDBC references       JDBC Data Access API – JDBC Technology Homepage  http://java.sun.com/docs/books/jdbc/ 24 .html JDBC Database Access – The Java Tutorial  JDBC Documentation  java.2/docs/api/java/sql/package-summary.sun.com/docs/books/tutorial/jdbc/index.sun.com/j2se/1.html http://java.4.sun.4.2/docs/guide/jdbc/getstart/GettingStartedTOC.fm.com/j2se/1.com/products/jdbc/index.sql package  JDBC Technology Guide: Getting Started  JDBC API Tutorial and Reference (book)  http://java.

sun.com/products/jdbc/index.com/j2se/1.JDBC       JDBC Data Access API – JDBC Technology Homepage  http://java.com/docs/books/tutorial/jdbc/index.4.2/docs/guide/jdbc/index.com/j2se/1.sun.sun.html JDBC Database Access – The Java Tutorial  JDBC Documentation  java.html http://java.2/docs/guide/jdbc/getstart/GettingStartedTOC.com/j2se/1.sun.sun.html http://java.com/docs/books/jdbc/ 25 .sql package  JDBC Technology Guide: Getting Started  JDBC API Tutorial and Reference (book)  http://java.4.2/docs/api/java/sql/package-summary.html http://java.html http://java.sun.fm.4.