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

What's hot (20)

PPTX
JSP - Java Server Page
Vipin Yadav
 
PPTX
Database Access With JDBC
Dharani Kumar Madduri
 
PPS
JSP Error handling
kamal kotecha
 
PPTX
Java Database Connectivity (JDBC)
Pooja Talreja
 
PDF
JDBC in Servlets
Eleonora Ciceri
 
PPTX
Java Servlet
Yoga Raja
 
PPT
Jsp sasidhar
Sasidhar Kothuru
 
PPT
Java Server Faces (JSF) - advanced
BG Java EE Course
 
PPTX
Database connect
Yoga Raja
 
PPTX
JSP- JAVA SERVER PAGES
Yoga Raja
 
PPT
Jsp ppt
Vikas Jagtap
 
PPTX
Java/Servlet/JSP/JDBC
FAKHRUN NISHA
 
PPT
J2EE - JSP-Servlet- Container - Components
Kaml Sah
 
PPTX
Jsp presentation
Sher Singh Bardhan
 
PPSX
Java server pages
Tanmoy Barman
 
PPT
JDBC Tutorial
Information Technology
 
PPS
Advance Java
Vidyacenter
 
PPT
Java servlet life cycle - methods ppt
kamal kotecha
 
PPT
Java Server Faces (JSF) - Basics
BG Java EE Course
 
PPS
Jsp element
kamal kotecha
 
JSP - Java Server Page
Vipin Yadav
 
Database Access With JDBC
Dharani Kumar Madduri
 
JSP Error handling
kamal kotecha
 
Java Database Connectivity (JDBC)
Pooja Talreja
 
JDBC in Servlets
Eleonora Ciceri
 
Java Servlet
Yoga Raja
 
Jsp sasidhar
Sasidhar Kothuru
 
Java Server Faces (JSF) - advanced
BG Java EE Course
 
Database connect
Yoga Raja
 
JSP- JAVA SERVER PAGES
Yoga Raja
 
Jsp ppt
Vikas Jagtap
 
Java/Servlet/JSP/JDBC
FAKHRUN NISHA
 
J2EE - JSP-Servlet- Container - Components
Kaml Sah
 
Jsp presentation
Sher Singh Bardhan
 
Java server pages
Tanmoy Barman
 
JDBC Tutorial
Information Technology
 
Advance Java
Vidyacenter
 
Java servlet life cycle - methods ppt
kamal kotecha
 
Java Server Faces (JSF) - Basics
BG Java EE Course
 
Jsp element
kamal kotecha
 

Viewers also liked (20)

PPT
Jdbc Dao it-slideshares.blogspot.com
phanleson
 
PPT
Jdbc in java
Asya Dudnik
 
PPTX
Data Access Layer как страховка на случай миграции СУБД
CUSTIS
 
PPT
Work with my_sql_-_database_in_java
Asya Dudnik
 
PPTX
Lecture data base programming part2
ganzorigb
 
PPTX
Lecture data base programming part1
ganzorigb
 
PPTX
Database Connectivity with JDBC
Dudy Ali
 
PPTX
Коллекции в Java
metaform
 
PPTX
Работа с БД в Java
metaform
 
PPTX
Lecture data base programming part3
ganzorigb
 
PPTX
PostgreSQL и JDBC: выжимаем все соки
Vladimir Sitnikov
 
PDF
Lecture03 p1
aa11bb11
 
PPTX
Unit testing
princezzlove
 
PPT
Introduction to the Servlet / JSP course
JavaEE Trainers
 
PPT
Software quality assurance
Prof. Erwin Globio
 
PPTX
Web application using JSP
Kaml Sah
 
PPT
jdbc
Gayatri Patel
 
PPT
Jsp
DSKUMAR G
 
PDF
1 intro of data structure course
Mahmoud Alfarra
 
PPTX
JDBC Driver Types
Rahul Sharma
 
Jdbc Dao it-slideshares.blogspot.com
phanleson
 
Jdbc in java
Asya Dudnik
 
Data Access Layer как страховка на случай миграции СУБД
CUSTIS
 
Work with my_sql_-_database_in_java
Asya Dudnik
 
Lecture data base programming part2
ganzorigb
 
Lecture data base programming part1
ganzorigb
 
Database Connectivity with JDBC
Dudy Ali
 
Коллекции в Java
metaform
 
Работа с БД в Java
metaform
 
Lecture data base programming part3
ganzorigb
 
PostgreSQL и JDBC: выжимаем все соки
Vladimir Sitnikov
 
Lecture03 p1
aa11bb11
 
Unit testing
princezzlove
 
Introduction to the Servlet / JSP course
JavaEE Trainers
 
Software quality assurance
Prof. Erwin Globio
 
Web application using JSP
Kaml Sah
 
1 intro of data structure course
Mahmoud Alfarra
 
JDBC Driver Types
Rahul Sharma
 
Ad

Similar to Data Access with JDBC (20)

PPT
Executing Sql Commands
phanleson
 
PPT
Executing Sql Commands
leminhvuong
 
PPT
Jdbc
smvdurajesh
 
PPTX
JDBC
Balwinder Kumar
 
PPT
30 5 Database Jdbc
phanleson
 
PPT
JDBC for CSQL Database
jitendral
 
PDF
Java OOP Programming language (Part 8) - Java Database JDBC
OUM SAOKOSAL
 
PPTX
Jdbc Java Programming
chhaichivon
 
PDF
Java JDBC
Jussi Pohjolainen
 
PPTX
Jdbc presentation
nrjoshiee
 
PPT
jdbc
vikram singh
 
PDF
Jdbc
mishaRani1
 
PPT
JDBC.ppt
Jayaprasanna4
 
PPTX
JDBC PPT(4).pptx java Database Connectivity
dhanushoneplus00
 
PDF
Java 1-contd
Mukesh Tekwani
 
PPTX
Database Programming Techniques
Raji Ghawi
 
PDF
java4th.pdf bilgisayar mühendisliği bölümü
Smeyyeztrk10
 
PPT
jdbc_presentation.ppt
DrMeenakshiS
 
Executing Sql Commands
phanleson
 
Executing Sql Commands
leminhvuong
 
30 5 Database Jdbc
phanleson
 
JDBC for CSQL Database
jitendral
 
Java OOP Programming language (Part 8) - Java Database JDBC
OUM SAOKOSAL
 
Jdbc Java Programming
chhaichivon
 
Jdbc presentation
nrjoshiee
 
JDBC.ppt
Jayaprasanna4
 
JDBC PPT(4).pptx java Database Connectivity
dhanushoneplus00
 
Java 1-contd
Mukesh Tekwani
 
Database Programming Techniques
Raji Ghawi
 
java4th.pdf bilgisayar mühendisliği bölümü
Smeyyeztrk10
 
jdbc_presentation.ppt
DrMeenakshiS
 
Ad

More from BG Java EE Course (20)

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

Recently uploaded (20)

PDF
Android Programming - Basics of Mobile App, App tools and Android Basics
Kavitha P.V
 
PPTX
Nitrogen rule, ring rule, mc lafferty.pptx
nbisen2001
 
PDF
epi editorial commitee meeting presentation
MIPLM
 
PDF
AI-Powered-Visual-Storytelling-for-Nonprofits.pdf
TechSoup
 
PPTX
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
PDF
Is Assignment Help Legal in Australia_.pdf
thomas19williams83
 
PPTX
Post Dated Cheque(PDC) Management in Odoo 18
Celine George
 
PDF
Governor Josh Stein letter to NC delegation of U.S. House
Mebane Rash
 
PPTX
How to Manage Allocation Report for Manufacturing Orders in Odoo 18
Celine George
 
PDF
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
PPTX
Controller Request and Response in Odoo18
Celine George
 
PPTX
Difference between write and update in odoo 18
Celine George
 
PPTX
TRANSLATIONAL AND ROTATIONAL MOTION.pptx
KIPAIZAGABAWA1
 
PPTX
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 
PPTX
How to Configure Re-Ordering From Portal in Odoo 18 Website
Celine George
 
PDF
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
PPTX
DAY 1_QUARTER1 ENGLISH 5 WEEK- PRESENTATION.pptx
BanyMacalintal
 
PPTX
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
PPTX
DIGITAL CITIZENSHIP TOPIC TLE 8 MATATAG CURRICULUM
ROBERTAUGUSTINEFRANC
 
PPTX
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 
Android Programming - Basics of Mobile App, App tools and Android Basics
Kavitha P.V
 
Nitrogen rule, ring rule, mc lafferty.pptx
nbisen2001
 
epi editorial commitee meeting presentation
MIPLM
 
AI-Powered-Visual-Storytelling-for-Nonprofits.pdf
TechSoup
 
CATEGORIES OF NURSING PERSONNEL: HOSPITAL & COLLEGE
PRADEEP ABOTHU
 
Is Assignment Help Legal in Australia_.pdf
thomas19williams83
 
Post Dated Cheque(PDC) Management in Odoo 18
Celine George
 
Governor Josh Stein letter to NC delegation of U.S. House
Mebane Rash
 
How to Manage Allocation Report for Manufacturing Orders in Odoo 18
Celine George
 
Reconstruct, Restore, Reimagine: New Perspectives on Stoke Newington’s Histor...
History of Stoke Newington
 
Controller Request and Response in Odoo18
Celine George
 
Difference between write and update in odoo 18
Celine George
 
TRANSLATIONAL AND ROTATIONAL MOTION.pptx
KIPAIZAGABAWA1
 
HUMAN RESOURCE MANAGEMENT: RECRUITMENT, SELECTION, PLACEMENT, DEPLOYMENT, TRA...
PRADEEP ABOTHU
 
How to Configure Re-Ordering From Portal in Odoo 18 Website
Celine George
 
Aprendendo Arquitetura Framework Salesforce - Dia 03
Mauricio Alexandre Silva
 
DAY 1_QUARTER1 ENGLISH 5 WEEK- PRESENTATION.pptx
BanyMacalintal
 
grade 5 lesson matatag ENGLISH 5_Q1_PPT_WEEK4.pptx
SireQuinn
 
DIGITAL CITIZENSHIP TOPIC TLE 8 MATATAG CURRICULUM
ROBERTAUGUSTINEFRANC
 
Identifying elements in the story. Arrange the events in the story
geraldineamahido2
 

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* ##