SlideShare a Scribd company logo
Data Access with JDBC Svetlin Nakov Bulgarian Association of Software Developers www.devbg.org
Contents Introduction to JDBC Querying the database Different statements Handling exceptions Transactions Best practices
JDBC Technology Overview
About JDBC JDBC is a standard interface for connecting to relational databases from Java The JDBC Core API package in  java.sql JDBC 2.0 Optional Package API in  javax.sql JDBC 3.0 API includes the Core API and Optional Package API
JDBC Architecture Application Connection Driver Manager Statement Result Set Driver Driver Driver Database Database Database
JDBC Components Driver Manager Loads database drivers, and manages the connection between application & driver Driver Translates API calls to operations for a specific data source Connection A session between an application and a database driver
JDBC Components (2) Statement A SQL statement to perform a query or an update operation Metadata Information about the returned data, driver and the database Result Set Logical set of columns and rows returned by executing a statement
Data Access with JDBC Querying the Database
Stage 1: Loading Drivers Loading the JDBC driver is done by a single line of code: Your driver documentation will give you the class name to use Loading Oracle JDBC driver Loading the JDBC-ODBC bridge driver  Class.forName(&quot; < jdbc  d river  class> &quot;);   Class.forName(&quot;oracle.jdbc.driver.OracleDriver&quot;);  Class.forName(&quot;sun.jdbc.odbc.JdbcOdbcDriver&quot;);
Stage 2: Establishing a Connection The following line of code illustrates the process: If you are using the JDBC-ODBC bridge driver, the JDBC URL will start with &quot; jdbc:odbc: &quot; If you are using a JDBC driver developed by a third party, the documentation will tell you what subprotocol to use Connection con   =   DriverManager. getConnection( &quot; url &quot; ,   &quot;user&quot;,   &quot;pass&quot;);
Stage 2: Establishing a Connection to ODBC Connecting to ODBC driver – example ODBC data source is called &quot; Library &quot;  DBMS login name is &quot; admin &quot; The password is &quot; secret &quot; Establishing a connection: Connection dbCon = DriverManager. getConnection(&quot;jdbc:odbc:Library&quot;, &quot;admin&quot;, &quot;secret&quot;);
Stage 2: Establishing a Connection to Oracle Connecting to Oracle – example The server is Oracle 10g Express Edition, locally installed Oracle database schema is called &quot; HR &quot;  The password is &quot; hr &quot; Establishing a connection: Connection dbCon = DriverManager.getConnection( &quot;jdbc:oracle:thin:@localhost:1521/xe&quot;, &quot;HR&quot;, &quot;hr&quot;);
Stage 3: Creating Statement A  Statement  object sends the SQL commands to the DBMS executeQuery()  is used for  SELECT  statements executeUpdate()  is used for statements that create/modify tables  An instance of active  Connection  is used to create a  Statement  object Connection dbCon = DriverManager.getConnection( &quot;jdbc:odbc:Library&quot;, &quot;admin&quot;, &quot;secret&quot;); Statement stmt =  dbCon.createStatement() ;
Stage 4: Executing Query executeQuery()  executes SQL command through a previously created statement Returns the results in a  ResultSet  object Connection dbCon = DriverManager.getConnection( &quot;jdbc:odbc:Library&quot;, &quot;admin&quot;, &quot;secret&quot;); Statement stmt = dbCon.createStatement(); ResultSet rs =  stmt.executeQuery ( &quot;SELECT first_name FROM employees&quot;);
Stage 4: Executing Statement executeUpdate()  is used to submit DML/DDL SQL statements DML is used to manipulate existing data in objects (using  UPDATE ,  INSERT ,  DELETE  statements) DDL is used to manipulate database objects ( CREATE ,  ALTER ,  DROP ) Statement stmt = dbCon.createStatement(); int rowsAffected =  stmt.executeUpdate ( &quot;UPDATE employees SET salary = salary*1.2&quot;);
Stage 5: Process The Returned Results The  ResultSet  object Maintains a cursor pointing to its current row of data Provides methods to retrieve column values ResultSet  rs = stmt.executeQuery( &quot;SELECT last_name, salary FROM employees&quot;); while (rs .next() ) { String name = rs .getString (&quot;last_name&quot;); double salary = rs .getDouble (&quot;salary&quot;); System.out.println(name + &quot; &quot; + salary); }
Stage 6: Closing the Connection Explicitly close a  Connection ,  Statement , and  ResultSet  to release resources that are no longer needed try { Connection conn = ...;  Statement stmt = ...; ResultSet rset = stmt.executeQuery( ...);   ... } finally // clean up rset.close();  stmt.close();  conn.close(); }
SQLException SQL statements can throw  java.sql .  SQLException  during their execution try  { rset = stmt.executeQuery( &quot;SELECT first_name, last_name FROM employee&quot;); } catch (SQLException sqlex) { ... // Handle SQL errors here } finally { // Clean up all used resources try { if (rset != null) rset.close();  } catch (SQLException sqlex)  {  ... // Ignore closing errors } ... }
Querying Oracle through JDBC Live Demo
JDBC Statements Statement ,  PreparedStatement  and  CallableStatement  Interfaces
Submitting DML Statements That Change the Database Create an empty statement object: Use  executeUpdate()  to execute the statement: Example: Statement stmt = conn.createStatement(); int count = stmt.executeUpdate(sql_dml_statement); Statement stmt = conn.createStatement(); int rowsDeleted = stmt.executeUpdate(&quot;DELETE FROM  order_items WHERE order_id = 2354&quot;);
Submitting DDL Statements Create an empty statement object: Use  executeUpdate()  to execute the statement: Example: Statement stmt = conn.createStatement(); int count = stmt.executeUpdate(sql_ ddl _statement); Statement stmt = conn.createStatement(); stmt.executeUpdat e (&quot; CREATE TABLE  temp(col1 NUMBER(5,2), col2 VARCHAR2(30)) &quot;);
Unknown Statements Create an empty statement object Use  execute()  to execute the statement Process the statement accordingly Statement stmt = conn.createStatement(); boolean result = stmt.execute(SQLstatement);  if (result) {   // was a query - process results ResultSet r = stmt.getResultSet(); ... } else { // was an update or DDL - process result   int count = stmt.getUpdateCount(); ... }
Prepared Statements PreparedStatement  is used to Execute a statement that takes parameters Execute given statement many times String insert SQL  = &quot;INSERT INTO employees(&quot; + &quot;first_name, last_name, salary) VALUES(?,?,?)&quot;; PreparedStatement stmt = c on.prepareStatement(insert SQL ); stmt.setString( 1 ,  &quot;Svetlin&quot; ); stmt.setString( 2 ,  &quot;Nakov&quot; ); stmt.set Double (3,  25000.0 ); stmt.executeUpdate();
Retrieving Auto Generated Primary Key Some databases support &quot;auto increment&quot; primary key columns E. g. MS SQL Server, MS Access, MySQL, ... JDBC can retrieve auto generated keys // Insert row and return PK int rowCount = stmt.executeUpdate( &quot;INSERT INTO Messages(Msg) VALUES ('Test')&quot;, Statement.RETURN_GENERATED_KEYS); //  Get the auto generated  PK ResultSet rs = stmt.getGeneratedKeys(); rs.next(); long primaryKey = rs.getLong(1);
Retrieving Auto Generated Primary Key in Oracle Oracle does not support &quot;auto increment&quot; primary key Use sequences to generate unique values stmtSeq = dbCon.createStatement(); rsNextId = stmtSeq.executeQuery( &quot;SELECT <some_sequence>.nextval FROM dual&quot;); rsNextId.next(); long nextId = rsNextId.getLong(1);  psIns = dbCon.prepareStatement( &quot;INSERT INTO Table(id, ...) VALUES(?, ?)&quot;); psIns.setLong(1, nextId); psIns.setString(2, ...); psIns.executeUpdate();
Callable Statements CallableStatement  interface: Is used for executing stored procedures Can pass input parameters Can retrieve output parameters Example: CallableStatement callStmt = dbCon.prepareCall(&quot;call SP_Insert_Msg(?,?)&quot;); callStmt.setString(1, msgText); callStmt.registerOutParameter(2, Types.BIGINT); callStmt.executeUpdate(); long id = callStmt.getLong(2);
JDBC Statements Live Demo
Transactions Management in JDBC
Database Transactions A  database transaction  is a set of database operations that must be either entirely completed or aborted A simple transaction is usually in this form: Begin the transaction Execute several SQL DML statements Commit the transaction If one of the SQL statements fails, rollback the entire transaction
JDBC Transactions JDBC transaction mode: Auto-commit  by default Can be turned off by calling  setAutoCommit(false) In auto-commit mode each statement is treated as a separate transaction If the auto-commit mode is off, no changes will be committed until  commit()  is invoked Auto-commit mode can be turned back on by calling  setAutoCommit(true )
JDBC Transactions –Example If we don’t want certain changes to be made permanent, we can issue  rollback () dbCon.setAutoCommit(false); try { Statement stmt = con.createStatement(); stmt.executeUpdate(&quot;INSERT INTO Groups   &quot; + &quot;VALUES   (101, ' Administrators ')&quot;); stmt.executeUpdate(&quot;INSERT INTO Users &quot; + &quot;VALUES (NULL, 'Mary', 101)&quot;); dbCon.commit(); } catch (Exception ex) { dbCon.rollback(); throw ex; }
Transactions in JDBC Live Demo
JDBC Advanced Features and Best Practices
Database Specific Properties You can pass database specific information to the database by using Properties object Example for Oracle database: Properties props = new java.util.Properties(); props.put(&quot;user&quot;, &quot;scott&quot;); props.put(&quot;password&quot;, &quot;tiger&quot;); props.put(&quot;defaultRowPrefetch&quot;, &quot;30&quot;); props.put(&quot;defaultBatchValue&quot;, &quot;5&quot;); Connection dbCon = DriverManger.getConnection( &quot;jdbc:oracle:thin:@hoststring&quot;, props);
Connection Pool Connection pool contains a number of open database connections There are a few choices when using connection pool: Depend on the application server  Use JDBC 2.0 interfaces ( ConnectionPoolDataSource  and  PooledConnection ) Create your own connection pool
Optimal Isolation Level You can set the transaction isolation level by calling  setTransactionIsolation( level ) Transaction Level Permitted Phenomena Impact Dirty Reads Non-Repeatable Reads Phantom Reads TRANSACTION_NONE   - - - FASTEST TRANSACTION_READ_UNCOMMITED   YES YES YES FASTEST TRANSACTION_READ_COMMITED   NO YES YES FAST TRANSACTION_REPEATABLE_READ   NO NO YES MEDIUM TRANSACTION_SERIALIZABLE   NO NO NO SLOW
ResultSet Metadata ResultSetMetaData  class Used to get information about the types and properties of the columns in a  ResultSet  object ResultSet rs = stmt.executeQuery( &quot;SELECT  *  FROM employees&quot;); ResultSetMetaData rsm = rs.getMetaData(); int number = rsm.getColumnCount(); f or (int i=0; i<number;   i++)  { System.out.println(rsm.getColumnName(i)); }
Close Unneeded Resources Closing connections, statements and result sets explicitly allows garbage collector to recollect memory and free resources as early as possible Close statement object as soon as you finish working with them Use  try-finally  statement to guarantee that resources will be freed even in case of exception
Choose the Right Statement Use  PreparedStatement  when you execute the same statement more than once Use  CallableStatement  when you want result from multiple and complex statements for a single request
Use Batch Updates/Retrieval Send multiple queries to reduce the number of JDBC calls and improve performance: You can improve performance by increasing number of rows to be fetched at a time statement.addBatch(&quot;sql_query1&quot;); statement.addBatch(&quot;sql_query2&quot;); statement.addBatch(&quot;sql_query3&quot;); statement.executeBatch(); s tatement.setFetchSize(30);
Optimize the SQL Queries Bad: Good: Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery( &quot; SELECT  *  FROM   EMPLOYEE   WHERE   ID = 1 &quot;); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery( &quot; SELECT   SALARY   FROM   EMPLOYEE   WHERE   ID=1 &quot;);
Problems Write a program that prints the names of all employees and their salaries from the standard HR schema in Oracle 10g. Don't forget to ensure that all exceptions are handled appropriately and used resources are cleaned. Write a program that reads a last name and a salary range from the console and prints all matched employees and their salaries from the standard HR schema in Oracle 10g. Use  PreparedStatement  with parameters. Handle the possible exceptions and close all used resources.
Problems (2) Write a program that creates a table  Countries(country_id, country_name)  and a sequence  SEQ_Countries . Define a class  Country  with the same fields like the columns in the  Countries  table. Write a method to insert new country. Write a method to list all countries (it should return  Country[] ). Write a method to find country by  country_id . Write a method to find country by part of its name. Finally write a method to drop the  Countries  table and the sequence  SEQ_Countries . Test all methods.
Problems (3) Create tables  Persons(person_id, person_name) ,   Accounts(account_id, acc_holder_id ,amount )  and  Log(log_id,   msg_date, log_msg) .  Define sequences for populating the primary keys in these tables (without triggers). Write stored procedures for inserting persons, accounts and log messages and Java methods that call them. Write method for transferring funds between accounts. It should keep track of all successful transfers in the  Log  table. Use transactions to maintain data consistency.
Homework Write a program that prints the names of all employees, their managers and departments from the standard HR schema in Oracle 10g. Handle the possible exceptions and close all used resources. Write a program that reads a department name from the console and prints all employees in this department and their average salary. Use the standard HR schema in Oracle 10g. Use  PreparedStatement  with parameters. Handle the possible exceptions and close all used resources.
Homework (2) Write a program that creates tables  Users(user_id, user_name, group_id)  and  Groups(group_id, group_name)  along with sequences fro populating their primary keys. Write classes  User  and  Group  that correspond to these tables. Write methods for adding new users and groups. Write methods for listing all groups, all users and all users by given group. Write methods for updating and deleting users and groups. Finally write a method to drop the tables  Users  and  Groups  and their sequences. Test all these methods. Handle the exceptions appropriately and close all used resources.
Homework (3) Modify the previous program to add also the table  Log(log_id, msg_date, msg_text)  that keeps track of all changes in the all other tables. Modify all methods to maintain the log. Don't forget to use transactions if a business operation modifies several tables. Add a method for adding user and group in the same time (by given user name and group name). If the group does not exists, it should be created on demand. Use transactions to guarantee the data consistency. Don't forget to register the operations in the logs.

More Related Content

PPS
Jdbc api
PPT
Web Applications and Deployment
PPT
JDBC Java Database Connectivity
PPS
Jdbc example program with access and MySql
PDF
JAVA EE DEVELOPMENT (JSP and Servlets)
PPT
Java Server Pages
PPT
JDBC – Java Database Connectivity
PPT
Jdbc ppt
Jdbc api
Web Applications and Deployment
JDBC Java Database Connectivity
Jdbc example program with access and MySql
JAVA EE DEVELOPMENT (JSP and Servlets)
Java Server Pages
JDBC – Java Database Connectivity
Jdbc ppt

What's hot (20)

PPTX
JSP - Java Server Page
PPTX
Database Access With JDBC
PPS
JSP Error handling
PPTX
Java Database Connectivity (JDBC)
PDF
JDBC in Servlets
PPTX
Java Servlet
PPT
Jsp sasidhar
PPT
Java Server Faces (JSF) - advanced
PPTX
Database connect
PPTX
JSP- JAVA SERVER PAGES
PPT
Jsp ppt
PPTX
Java/Servlet/JSP/JDBC
PPT
J2EE - JSP-Servlet- Container - Components
PPTX
Jsp presentation
PPSX
Java server pages
PPT
JDBC Tutorial
PPS
Advance Java
PPT
Java servlet life cycle - methods ppt
PPT
Java Server Faces (JSF) - Basics
PPS
Jsp element
JSP - Java Server Page
Database Access With JDBC
JSP Error handling
Java Database Connectivity (JDBC)
JDBC in Servlets
Java Servlet
Jsp sasidhar
Java Server Faces (JSF) - advanced
Database connect
JSP- JAVA SERVER PAGES
Jsp ppt
Java/Servlet/JSP/JDBC
J2EE - JSP-Servlet- Container - Components
Jsp presentation
Java server pages
JDBC Tutorial
Advance Java
Java servlet life cycle - methods ppt
Java Server Faces (JSF) - Basics
Jsp element
Ad

Viewers also liked (20)

PPT
Jdbc Dao it-slideshares.blogspot.com
PPT
Jdbc in java
PPTX
Data Access Layer как страховка на случай миграции СУБД
PPT
Work with my_sql_-_database_in_java
PPTX
Lecture data base programming part2
PPTX
Lecture data base programming part1
PPTX
Database Connectivity with JDBC
PPTX
Коллекции в Java
PPTX
Работа с БД в Java
PPTX
Lecture data base programming part3
PPTX
PostgreSQL и JDBC: выжимаем все соки
PDF
Lecture03 p1
PPTX
Unit testing
PPT
Introduction to the Servlet / JSP course
PPT
Software quality assurance
PPTX
Web application using JSP
PPT
PPT
PDF
1 intro of data structure course
PPTX
JDBC Driver Types
Jdbc Dao it-slideshares.blogspot.com
Jdbc in java
Data Access Layer как страховка на случай миграции СУБД
Work with my_sql_-_database_in_java
Lecture data base programming part2
Lecture data base programming part1
Database Connectivity with JDBC
Коллекции в Java
Работа с БД в Java
Lecture data base programming part3
PostgreSQL и JDBC: выжимаем все соки
Lecture03 p1
Unit testing
Introduction to the Servlet / JSP course
Software quality assurance
Web application using JSP
1 intro of data structure course
JDBC Driver Types
Ad

Similar to Data Access with JDBC (20)

PPT
JDBC for CSQL Database
PDF
Lecture17
PPT
PPT
Sqlapi0.1
PPT
Jdbc
PPT
30 5 Database Jdbc
PPTX
JDBC ppt
PPT
JDBC Connecticity.ppt
PPT
PPT
4. Database Connectivity using JDBC .ppt
PPTX
Jdbc ppt
PPT
Executing Sql Commands
PPT
Executing Sql Commands
PPTX
PPTX
Lecture 1. java database connectivity
PPT
Java jdbc
PDF
Jdbc[1]
PDF
JDBC programming
DOC
Java database connectivity notes for undergraduate
PDF
JDBC for CSQL Database
Lecture17
Sqlapi0.1
Jdbc
30 5 Database Jdbc
JDBC ppt
JDBC Connecticity.ppt
4. Database Connectivity using JDBC .ppt
Jdbc ppt
Executing Sql Commands
Executing Sql Commands
Lecture 1. java database connectivity
Java jdbc
Jdbc[1]
JDBC programming
Java database connectivity notes for undergraduate

More from BG Java EE Course (20)

PPT
Rich faces
PPT
JSP Custom Tags
PPT
Unified Expression Language
PPT
Java Servlets
PPTX
HTML: Tables and Forms
PPTX
HTML Fundamentals
PPTX
WWW and HTTP
ODP
JavaScript and jQuery Fundamentals
ODP
Creating Web Sites with HTML and CSS
PPT
Processing XML with Java
PPT
Introduction to XML
PPT
Introduction to-sql
PPT
Introduction to-RDBMS-systems
PPT
Basic data-structures-v.1.1
PPT
Basic input-output-v.1.1
PPT
Strings v.1.1
PPT
Object-oriented concepts
PPT
Inheritance and Polymorphism
Rich faces
JSP Custom Tags
Unified Expression Language
Java Servlets
HTML: Tables and Forms
HTML Fundamentals
WWW and HTTP
JavaScript and jQuery Fundamentals
Creating Web Sites with HTML and CSS
Processing XML with Java
Introduction to XML
Introduction to-sql
Introduction to-RDBMS-systems
Basic data-structures-v.1.1
Basic input-output-v.1.1
Strings v.1.1
Object-oriented concepts
Inheritance and Polymorphism

Recently uploaded (20)

PDF
LDMMIA Reiki Yoga Workshop 15 MidTerm Review
PDF
2.Reshaping-Indias-Political-Map.ppt/pdf/8th class social science Exploring S...
PPTX
Revamp in MTO Odoo 18 Inventory - Odoo Slides
PPTX
vedic maths in python:unleasing ancient wisdom with modern code
PDF
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
PPTX
How to Manage Bill Control Policy in Odoo 18
PPTX
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
PPTX
Strengthening open access through collaboration: building connections with OP...
PPTX
Odoo 18 Sales_ Managing Quotation Validity
PPTX
Open Quiz Monsoon Mind Game Prelims.pptx
PDF
5.Universal-Franchise-and-Indias-Electoral-System.pdfppt/pdf/8th class social...
PPTX
Open Quiz Monsoon Mind Game Final Set.pptx
DOCX
UPPER GASTRO INTESTINAL DISORDER.docx
PDF
What Is Coercive Control? Understanding and Recognizing Hidden Abuse
PPTX
How to Manage Loyalty Points in Odoo 18 Sales
PDF
Mga Unang Hakbang Tungo Sa Tao by Joe Vibar Nero.pdf
PPTX
NOI Hackathon - Summer Edition - GreenThumber.pptx
PDF
3.The-Rise-of-the-Marathas.pdfppt/pdf/8th class social science Exploring Soci...
PPTX
IMMUNIZATION PROGRAMME pptx
PDF
High Ground Student Revision Booklet Preview
LDMMIA Reiki Yoga Workshop 15 MidTerm Review
2.Reshaping-Indias-Political-Map.ppt/pdf/8th class social science Exploring S...
Revamp in MTO Odoo 18 Inventory - Odoo Slides
vedic maths in python:unleasing ancient wisdom with modern code
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
How to Manage Bill Control Policy in Odoo 18
Introduction to Child Health Nursing – Unit I | Child Health Nursing I | B.Sc...
Strengthening open access through collaboration: building connections with OP...
Odoo 18 Sales_ Managing Quotation Validity
Open Quiz Monsoon Mind Game Prelims.pptx
5.Universal-Franchise-and-Indias-Electoral-System.pdfppt/pdf/8th class social...
Open Quiz Monsoon Mind Game Final Set.pptx
UPPER GASTRO INTESTINAL DISORDER.docx
What Is Coercive Control? Understanding and Recognizing Hidden Abuse
How to Manage Loyalty Points in Odoo 18 Sales
Mga Unang Hakbang Tungo Sa Tao by Joe Vibar Nero.pdf
NOI Hackathon - Summer Edition - GreenThumber.pptx
3.The-Rise-of-the-Marathas.pdfppt/pdf/8th class social science Exploring Soci...
IMMUNIZATION PROGRAMME pptx
High Ground Student Revision Booklet Preview

Data Access with JDBC

  • 1. Data Access with JDBC Svetlin Nakov Bulgarian Association of Software Developers www.devbg.org
  • 2. Contents Introduction to JDBC Querying the database Different statements Handling exceptions Transactions Best practices
  • 4. About JDBC JDBC is a standard interface for connecting to relational databases from Java The JDBC Core API package in java.sql JDBC 2.0 Optional Package API in javax.sql JDBC 3.0 API includes the Core API and Optional Package API
  • 5. JDBC Architecture Application Connection Driver Manager Statement Result Set Driver Driver Driver Database Database Database
  • 6. JDBC Components Driver Manager Loads database drivers, and manages the connection between application & driver Driver Translates API calls to operations for a specific data source Connection A session between an application and a database driver
  • 7. JDBC Components (2) Statement A SQL statement to perform a query or an update operation Metadata Information about the returned data, driver and the database Result Set Logical set of columns and rows returned by executing a statement
  • 8. Data Access with JDBC Querying the Database
  • 9. Stage 1: Loading Drivers Loading the JDBC driver is done by a single line of code: Your driver documentation will give you the class name to use Loading Oracle JDBC driver Loading the JDBC-ODBC bridge driver Class.forName(&quot; < jdbc d river class> &quot;); Class.forName(&quot;oracle.jdbc.driver.OracleDriver&quot;); Class.forName(&quot;sun.jdbc.odbc.JdbcOdbcDriver&quot;);
  • 10. Stage 2: Establishing a Connection The following line of code illustrates the process: If you are using the JDBC-ODBC bridge driver, the JDBC URL will start with &quot; jdbc:odbc: &quot; If you are using a JDBC driver developed by a third party, the documentation will tell you what subprotocol to use Connection con = DriverManager. getConnection( &quot; url &quot; , &quot;user&quot;, &quot;pass&quot;);
  • 11. Stage 2: Establishing a Connection to ODBC Connecting to ODBC driver – example ODBC data source is called &quot; Library &quot; DBMS login name is &quot; admin &quot; The password is &quot; secret &quot; Establishing a connection: Connection dbCon = DriverManager. getConnection(&quot;jdbc:odbc:Library&quot;, &quot;admin&quot;, &quot;secret&quot;);
  • 12. Stage 2: Establishing a Connection to Oracle Connecting to Oracle – example The server is Oracle 10g Express Edition, locally installed Oracle database schema is called &quot; HR &quot; The password is &quot; hr &quot; Establishing a connection: Connection dbCon = DriverManager.getConnection( &quot;jdbc:oracle:thin:@localhost:1521/xe&quot;, &quot;HR&quot;, &quot;hr&quot;);
  • 13. Stage 3: Creating Statement A Statement object sends the SQL commands to the DBMS executeQuery() is used for SELECT statements executeUpdate() is used for statements that create/modify tables An instance of active Connection is used to create a Statement object Connection dbCon = DriverManager.getConnection( &quot;jdbc:odbc:Library&quot;, &quot;admin&quot;, &quot;secret&quot;); Statement stmt = dbCon.createStatement() ;
  • 14. Stage 4: Executing Query executeQuery() executes SQL command through a previously created statement Returns the results in a ResultSet object Connection dbCon = DriverManager.getConnection( &quot;jdbc:odbc:Library&quot;, &quot;admin&quot;, &quot;secret&quot;); Statement stmt = dbCon.createStatement(); ResultSet rs = stmt.executeQuery ( &quot;SELECT first_name FROM employees&quot;);
  • 15. Stage 4: Executing Statement executeUpdate() is used to submit DML/DDL SQL statements DML is used to manipulate existing data in objects (using UPDATE , INSERT , DELETE statements) DDL is used to manipulate database objects ( CREATE , ALTER , DROP ) Statement stmt = dbCon.createStatement(); int rowsAffected = stmt.executeUpdate ( &quot;UPDATE employees SET salary = salary*1.2&quot;);
  • 16. Stage 5: Process The Returned Results The ResultSet object Maintains a cursor pointing to its current row of data Provides methods to retrieve column values ResultSet rs = stmt.executeQuery( &quot;SELECT last_name, salary FROM employees&quot;); while (rs .next() ) { String name = rs .getString (&quot;last_name&quot;); double salary = rs .getDouble (&quot;salary&quot;); System.out.println(name + &quot; &quot; + salary); }
  • 17. Stage 6: Closing the Connection Explicitly close a Connection , Statement , and ResultSet to release resources that are no longer needed try { Connection conn = ...; Statement stmt = ...; ResultSet rset = stmt.executeQuery( ...); ... } finally // clean up rset.close(); stmt.close(); conn.close(); }
  • 18. SQLException SQL statements can throw java.sql . SQLException during their execution try { rset = stmt.executeQuery( &quot;SELECT first_name, last_name FROM employee&quot;); } catch (SQLException sqlex) { ... // Handle SQL errors here } finally { // Clean up all used resources try { if (rset != null) rset.close(); } catch (SQLException sqlex) { ... // Ignore closing errors } ... }
  • 19. Querying Oracle through JDBC Live Demo
  • 20. JDBC Statements Statement , PreparedStatement and CallableStatement Interfaces
  • 21. Submitting DML Statements That Change the Database Create an empty statement object: Use executeUpdate() to execute the statement: Example: Statement stmt = conn.createStatement(); int count = stmt.executeUpdate(sql_dml_statement); Statement stmt = conn.createStatement(); int rowsDeleted = stmt.executeUpdate(&quot;DELETE FROM order_items WHERE order_id = 2354&quot;);
  • 22. Submitting DDL Statements Create an empty statement object: Use executeUpdate() to execute the statement: Example: Statement stmt = conn.createStatement(); int count = stmt.executeUpdate(sql_ ddl _statement); Statement stmt = conn.createStatement(); stmt.executeUpdat e (&quot; CREATE TABLE temp(col1 NUMBER(5,2), col2 VARCHAR2(30)) &quot;);
  • 23. Unknown Statements Create an empty statement object Use execute() to execute the statement Process the statement accordingly Statement stmt = conn.createStatement(); boolean result = stmt.execute(SQLstatement); if (result) { // was a query - process results ResultSet r = stmt.getResultSet(); ... } else { // was an update or DDL - process result int count = stmt.getUpdateCount(); ... }
  • 24. Prepared Statements PreparedStatement is used to Execute a statement that takes parameters Execute given statement many times String insert SQL = &quot;INSERT INTO employees(&quot; + &quot;first_name, last_name, salary) VALUES(?,?,?)&quot;; PreparedStatement stmt = c on.prepareStatement(insert SQL ); stmt.setString( 1 , &quot;Svetlin&quot; ); stmt.setString( 2 , &quot;Nakov&quot; ); stmt.set Double (3, 25000.0 ); stmt.executeUpdate();
  • 25. Retrieving Auto Generated Primary Key Some databases support &quot;auto increment&quot; primary key columns E. g. MS SQL Server, MS Access, MySQL, ... JDBC can retrieve auto generated keys // Insert row and return PK int rowCount = stmt.executeUpdate( &quot;INSERT INTO Messages(Msg) VALUES ('Test')&quot;, Statement.RETURN_GENERATED_KEYS); // Get the auto generated PK ResultSet rs = stmt.getGeneratedKeys(); rs.next(); long primaryKey = rs.getLong(1);
  • 26. Retrieving Auto Generated Primary Key in Oracle Oracle does not support &quot;auto increment&quot; primary key Use sequences to generate unique values stmtSeq = dbCon.createStatement(); rsNextId = stmtSeq.executeQuery( &quot;SELECT <some_sequence>.nextval FROM dual&quot;); rsNextId.next(); long nextId = rsNextId.getLong(1); psIns = dbCon.prepareStatement( &quot;INSERT INTO Table(id, ...) VALUES(?, ?)&quot;); psIns.setLong(1, nextId); psIns.setString(2, ...); psIns.executeUpdate();
  • 27. Callable Statements CallableStatement interface: Is used for executing stored procedures Can pass input parameters Can retrieve output parameters Example: CallableStatement callStmt = dbCon.prepareCall(&quot;call SP_Insert_Msg(?,?)&quot;); callStmt.setString(1, msgText); callStmt.registerOutParameter(2, Types.BIGINT); callStmt.executeUpdate(); long id = callStmt.getLong(2);
  • 30. Database Transactions A database transaction is a set of database operations that must be either entirely completed or aborted A simple transaction is usually in this form: Begin the transaction Execute several SQL DML statements Commit the transaction If one of the SQL statements fails, rollback the entire transaction
  • 31. JDBC Transactions JDBC transaction mode: Auto-commit by default Can be turned off by calling setAutoCommit(false) In auto-commit mode each statement is treated as a separate transaction If the auto-commit mode is off, no changes will be committed until commit() is invoked Auto-commit mode can be turned back on by calling setAutoCommit(true )
  • 32. JDBC Transactions –Example If we don’t want certain changes to be made permanent, we can issue rollback () dbCon.setAutoCommit(false); try { Statement stmt = con.createStatement(); stmt.executeUpdate(&quot;INSERT INTO Groups &quot; + &quot;VALUES (101, ' Administrators ')&quot;); stmt.executeUpdate(&quot;INSERT INTO Users &quot; + &quot;VALUES (NULL, 'Mary', 101)&quot;); dbCon.commit(); } catch (Exception ex) { dbCon.rollback(); throw ex; }
  • 33. Transactions in JDBC Live Demo
  • 34. JDBC Advanced Features and Best Practices
  • 35. Database Specific Properties You can pass database specific information to the database by using Properties object Example for Oracle database: Properties props = new java.util.Properties(); props.put(&quot;user&quot;, &quot;scott&quot;); props.put(&quot;password&quot;, &quot;tiger&quot;); props.put(&quot;defaultRowPrefetch&quot;, &quot;30&quot;); props.put(&quot;defaultBatchValue&quot;, &quot;5&quot;); Connection dbCon = DriverManger.getConnection( &quot;jdbc:oracle:thin:@hoststring&quot;, props);
  • 36. Connection Pool Connection pool contains a number of open database connections There are a few choices when using connection pool: Depend on the application server Use JDBC 2.0 interfaces ( ConnectionPoolDataSource and PooledConnection ) Create your own connection pool
  • 37. Optimal Isolation Level You can set the transaction isolation level by calling setTransactionIsolation( level ) Transaction Level Permitted Phenomena Impact Dirty Reads Non-Repeatable Reads Phantom Reads TRANSACTION_NONE - - - FASTEST TRANSACTION_READ_UNCOMMITED YES YES YES FASTEST TRANSACTION_READ_COMMITED NO YES YES FAST TRANSACTION_REPEATABLE_READ NO NO YES MEDIUM TRANSACTION_SERIALIZABLE NO NO NO SLOW
  • 38. ResultSet Metadata ResultSetMetaData class Used to get information about the types and properties of the columns in a ResultSet object ResultSet rs = stmt.executeQuery( &quot;SELECT * FROM employees&quot;); ResultSetMetaData rsm = rs.getMetaData(); int number = rsm.getColumnCount(); f or (int i=0; i<number; i++) { System.out.println(rsm.getColumnName(i)); }
  • 39. Close Unneeded Resources Closing connections, statements and result sets explicitly allows garbage collector to recollect memory and free resources as early as possible Close statement object as soon as you finish working with them Use try-finally statement to guarantee that resources will be freed even in case of exception
  • 40. Choose the Right Statement Use PreparedStatement when you execute the same statement more than once Use CallableStatement when you want result from multiple and complex statements for a single request
  • 41. Use Batch Updates/Retrieval Send multiple queries to reduce the number of JDBC calls and improve performance: You can improve performance by increasing number of rows to be fetched at a time statement.addBatch(&quot;sql_query1&quot;); statement.addBatch(&quot;sql_query2&quot;); statement.addBatch(&quot;sql_query3&quot;); statement.executeBatch(); s tatement.setFetchSize(30);
  • 42. Optimize the SQL Queries Bad: Good: Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery( &quot; SELECT * FROM EMPLOYEE WHERE ID = 1 &quot;); Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery( &quot; SELECT SALARY FROM EMPLOYEE WHERE ID=1 &quot;);
  • 43. Problems Write a program that prints the names of all employees and their salaries from the standard HR schema in Oracle 10g. Don't forget to ensure that all exceptions are handled appropriately and used resources are cleaned. Write a program that reads a last name and a salary range from the console and prints all matched employees and their salaries from the standard HR schema in Oracle 10g. Use PreparedStatement with parameters. Handle the possible exceptions and close all used resources.
  • 44. Problems (2) Write a program that creates a table Countries(country_id, country_name) and a sequence SEQ_Countries . Define a class Country with the same fields like the columns in the Countries table. Write a method to insert new country. Write a method to list all countries (it should return Country[] ). Write a method to find country by country_id . Write a method to find country by part of its name. Finally write a method to drop the Countries table and the sequence SEQ_Countries . Test all methods.
  • 45. Problems (3) Create tables Persons(person_id, person_name) , Accounts(account_id, acc_holder_id ,amount ) and Log(log_id, msg_date, log_msg) . Define sequences for populating the primary keys in these tables (without triggers). Write stored procedures for inserting persons, accounts and log messages and Java methods that call them. Write method for transferring funds between accounts. It should keep track of all successful transfers in the Log table. Use transactions to maintain data consistency.
  • 46. Homework Write a program that prints the names of all employees, their managers and departments from the standard HR schema in Oracle 10g. Handle the possible exceptions and close all used resources. Write a program that reads a department name from the console and prints all employees in this department and their average salary. Use the standard HR schema in Oracle 10g. Use PreparedStatement with parameters. Handle the possible exceptions and close all used resources.
  • 47. Homework (2) Write a program that creates tables Users(user_id, user_name, group_id) and Groups(group_id, group_name) along with sequences fro populating their primary keys. Write classes User and Group that correspond to these tables. Write methods for adding new users and groups. Write methods for listing all groups, all users and all users by given group. Write methods for updating and deleting users and groups. Finally write a method to drop the tables Users and Groups and their sequences. Test all these methods. Handle the exceptions appropriately and close all used resources.
  • 48. Homework (3) Modify the previous program to add also the table Log(log_id, msg_date, msg_text) that keeps track of all changes in the all other tables. Modify all methods to maintain the log. Don't forget to use transactions if a business operation modifies several tables. Add a method for adding user and group in the same time (by given user name and group name). If the group does not exists, it should be created on demand. Use transactions to guarantee the data consistency. Don't forget to register the operations in the logs.

Editor's Notes

  • #2: (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • #5: * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • #6: * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • #7: * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • #8: * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • #9: * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • #10: * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ## If, for example, you want to use the JDBC-ODBC Bridge driver, the following code will load it: Class.forName(&amp;quot;sun.jdbc.odbc.JdbcOdbcDriver&amp;quot;);
  • #11: * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ## If you are using the JDBC-ODBC Bridge driver, the JDBC URL will start with jdbc:odbc: - The rest of the URL is generally your data source name or database system. If you are using a JDBC driver developed by a third party, the documentation will tell you what subprotocol to use. - That is, what to put after jdbc: in the JDBC URL. For example, if the driver developer has registered the name foo as the subprotocol, the first and second parts of the JDBC URL will be jdbc:foo: . If one of the drivers you loaded recognizes the JDBC URL supplied to the method DriverManager.getConnection , that driver will establish a connection to the DBMS specified in the JDBC URL. The DriverManager class, true to its name, manages all of the details of establishing the connection for you behind the scenes. Unless you are writing a driver, you will probably never use any of the methods in the interface Driver , and the only DriverManager method you really need to know is DriverManager.getConnection .
  • #12: * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ## The connection returned by the method DriverManager.getConnection is an open connection you can use to create JDBC statements that pass your SQL statements to the DBMS. In this example, con is an open connection, and we will use it in the examples that follow.
  • #13: * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ## The connection returned by the method DriverManager.getConnection is an open connection you can use to create JDBC statements that pass your SQL statements to the DBMS. In this example, con is an open connection, and we will use it in the examples that follow.
  • #14: * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ## At this point stmt exists, but it does not have an SQL statement to pass on to the DBMS. We need to supply that to the method we use to execute stmt .
  • #15: * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ## This method takes a SQL statement as input and returns a JDBC ResultSet object. T his statement follows standard SQL syntax.
  • #17: * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ## The ResultSet object is a table of data representing a database result set, which is generated by executing a statement that queries the database. A ResultSet object maintains a cursor pointing to its current row of data. Initially the cursor is positioned before the first row. A default ResultSet object is not updateable and has a cursor that moves forward only. Thus, it is possible to iterate through it only once and only from the first row to the last row. New methods in the JDBC 2.0 API make it possible to produce ResultSet objects that are scrollable and updateable.
  • #18: * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ## You must explicitly close all ResultSet and Statement objects after you finish using them. The close() methods clean up memory and release database cursors, so if you do not explicitly close your ResultSet and Statement objects, serious memory leaks may occur, and you may run out of cursors in the database. You then need to close the connection.
  • #19: * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ## Use standard Java error handling methods to handle the SQL errors
  • #20: * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • #21: * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • #22: * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ## executeUpdate() returns an int containing t he row count, for an INSERT , UPDATE , or DELETE statement.
  • #23: * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ## executeUpdate() returns an int containing 0, for a statement with no return value, such as a SQL DDL statement.
  • #24: * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ## An application may not know whether a given statement will return a result set until the statement has been executed. In addition, some stored procedures may return several different result sets and update counts. JDBC provides a mechanism so that an application can execute a statement and then process an arbitrary collection of result sets and update counts. The mechanism is based on the use of a general execute() method and then calls to three other methods: getResultSet , getUpdateCount , and getMoreResults . These methods enable an application to explore the statement results one at a time and to determine whether a given result is a result set or an update count. execute() returns true if the result of the statement is a result set; it returns false if the result of the statement is an update count. You can then call either getResultSet() or getUpdateCount() on the statement.
  • #25: * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ## Prepared statements can execute select SQL statements also: String query =&amp;quot;SELECT Name from CS4400 where SSN=?&amp;quot;; PreparedStatement stmt = con.prepareStatement(query); stmt.setInt(1,SSN); ResultSet rs = stmt.executeUpdate(); while (rs.next()) System.out.println(rs.getString(Name);
  • #28: * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • #29: * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • #30: * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • #31: * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ## If one of queries fails the database system may rollback the entire transaction : The database may rollback just the failed query. This behaviour is dependent on the DBMS in use and how it is set up. The transaction can also be rolled back manually at any time before the commit.
  • #32: * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • #33: * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ## Any changes made since the last commit will be ignored – usually rollback is used in combination with Java’s exception handling ability to recover from unpredictable errors.
  • #34: * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • #35: * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • #36: * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ## For Oracle database you can pass default number of rows that must be pre-fetched from the database server and the default batch value that triggers an execution request. Oracle has default value as 10 for both properties. By increasing the value of these properties, you can reduce the number of database calls which in turn improves performance.
  • #37: * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ## Creating a connection to the database server is expensive. It is even more expensive if the server is located on another machine. The connection pool has open connections between minimum and maximum number that you specify. The pool expands and shrinks between minimum and maximum size depending on incremental capacity. You need to give minimum, maximum and incremental sizes as properties to the pool in order to maintain that functionality. You get the connection from the pool rather directly . Depend on application server : Generally all the application servers support connection pools. Application server creates the connection pool on behalf of you when it starts. You need to give properties like min, max and incremental sizes to the application server. Use JDBC 2.0 interfaces (ConnectionPoolDataSource and PooledConnection) : If your driver implements these interfaces Create your own connection pool : If you are not using any application server or JDBC 2.0  compatible driver.
  • #38: * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ## Isolation level represent how a database maintains data integrity against the problems like dirty reads, phantom reads and non-repeatable reads which can occur due to concurrent transactions. java.sql.Connection interface provides  methods and constants to avoid the above mentioned problems by setting different isolation levels. Choosing a right isolation level for your program depends upon your application&apos;s requirement. In single application itself the requirement generally changes, suppose if you write a program for searching a product catalog from your database then you can easily choose TRANSACTION_READ_UNCOMMITED because you need not worry about the problems that are mentioned above, some other program can insert records at the same time, you don&apos;t have to bother much about that insertion. Obviously this improves performance significantly.
  • #39: * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • #40: * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ## When you use a connection pool, closing connection means that it returns back to the connection pool (it is not really closed)
  • #41: * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ## PreparedStatement gives better performance when compared to Statement because it is pre-parsed and pre-compiled by the database once for the first time and then onwards it reuses the parsed and compiled statement. Because of this feature, it significantly improves performance when a statement executes repeatedly, It reduces the overload incurred by parsing and compiling. CallableStatement gives better performance when compared to PreparedStatement and Statement when there is a requirement for single request to process multiple complex statements. It parses and stores the stored procedures in the database and does all the work at database itself that in turn improves performance. But we loose java portability and we have to depend up on database specific stored procedures.
  • #42: * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ## All three types of statements have these methods to do batch update. You can get the default number of rows that is provided by the driver by calling Statement.getFetchSize()
  • #43: * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ## Do not use general queries. The second call returns the required data and reduces unnecessary data retrieval.
  • #44: * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • #45: * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • #46: * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##