48
Data Access Data Access with JDBC with JDBC Svetlin Svetlin Nakov Nakov Bulgarian Association Bulgarian Association of Software of Software Developers Developers www.devbg.org

Data Access with JDBC

Embed Size (px)

DESCRIPTION

Data Access with JDBC - http://javaeecourse.devg.org

Citation preview

Page 1: Data Access with JDBC

Data Access Data Access with JDBCwith JDBCSvetlin NakovSvetlin Nakov

Bulgarian Association of Bulgarian Association of Software DevelopersSoftware Developers

www.devbg.org

Page 2: Data Access with JDBC

ContentsContents

1.1. Introduction to JDBCIntroduction to JDBC

2.2. Querying the databaseQuerying the database

3.3. Different statementsDifferent statements

4.4. Handling exceptionsHandling exceptions

5.5. TransactionsTransactions

6.6. Best practicesBest practices

Page 3: Data Access with JDBC

JDBCJDBC Technology OverviewTechnology Overview

Page 4: Data Access with JDBC

About JDBCAbout JDBC

• JDBC is a standard interface for JDBC is a standard interface for connecting to relational databases connecting to relational databases from Javafrom Java

• The JDBC Core API package in The JDBC Core API package in java.sqljava.sql

• JDBC 2.0 Optional Package API in JDBC 2.0 Optional Package API in javax.sqljavax.sql

• JDBC 3.0 API includes the Core API JDBC 3.0 API includes the Core API and Optional Package APIand Optional Package API

Page 5: Data Access with JDBC

JDBC ArchitectureJDBC Architecture

Application

Connection

Driver Manager

Statement Result Set

Driver Driver Driver

DatabaseDatabaseDatabaseDatabase DatabaseDatabaseDatabaseDatabase DatabaseDatabaseDatabaseDatabase

Page 6: Data Access with JDBC

JDBC ComponentsJDBC Components

• Driver ManagerDriver Manager

• Loads database drivers, and manages the Loads database drivers, and manages the connection between application & driverconnection between application & driver

• DriverDriver

• Translates API calls to operations for a Translates API calls to operations for a specific data sourcespecific data source

• ConnectionConnection

• A session between an application and a A session between an application and a database driverdatabase driver

Page 7: Data Access with JDBC

JDBC Components (2)JDBC Components (2)

• StatementStatement

• A SQL statement to perform a query or A SQL statement to perform a query or an update operationan update operation

• MetadataMetadata

• Information about the returned data, Information about the returned data, driver and the databasedriver and the database

• Result SetResult Set

• Logical set of columns and rows Logical set of columns and rows returned by executing a statementreturned by executing a statement

Page 8: Data Access with JDBC

Data Access Data Access with JDBCwith JDBC

Querying the DatabaseQuerying the Database

Page 9: Data Access with JDBC

Stage 1: Loading DriversStage 1: Loading Drivers

• Loading the JDBC driver is done by a Loading the JDBC driver is done by a single line of code:single line of code:

• Your driver documentation will give you Your driver documentation will give you the class name to usethe class name to use

• Loading Oracle JDBC driverLoading Oracle JDBC driver

• Loading the JDBC-ODBC bridge driver Loading the JDBC-ODBC bridge driver

Class.forName("Class.forName("<<jdbcjdbc d driverriver class> class>");");

Class.forName("oracle.jdbc.driver.OracleDriver"); Class.forName("oracle.jdbc.driver.OracleDriver");

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Page 10: Data Access with JDBC

Stage 2: Establishing a Stage 2: Establishing a ConnectionConnection

• The following line of code illustrates the The following line of code illustrates the process:process:

• If you are using the JDBC-ODBC bridge If you are using the JDBC-ODBC bridge driver, the JDBC URL will start with driver, the JDBC URL will start with ""jdbc:odbc:jdbc:odbc:""

• If you are using a JDBC driver developed by If you are using a JDBC driver developed by a third party, the documentation will tell you a third party, the documentation will tell you what subprotocol to usewhat subprotocol to use

Connection conConnection con == DriverManager.DriverManager. getConnection(getConnection(""urlurl"",, "user","user", "pass");"pass");

Page 11: Data Access with JDBC

Stage 2: Establishing a Stage 2: Establishing a Connection to ODBCConnection to ODBC

• Connecting to ODBC driver – exampleConnecting to ODBC driver – example

• ODBC data source is called "ODBC data source is called "LibraryLibrary" "

• DBMS login name is "DBMS login name is "adminadmin""

• The password is "The password is "secretsecret""

• Establishing a connection:Establishing a connection:

Connection dbCon = DriverManager.Connection dbCon = DriverManager. getConnection("jdbc:odbc:Library",getConnection("jdbc:odbc:Library", "admin","admin", "secret");"secret");

Page 12: Data Access with JDBC

Stage 2: Establishing a Stage 2: Establishing a Connection to OracleConnection to Oracle

• Connecting to Oracle – exampleConnecting to Oracle – example

• The server is Oracle 10g Express The server is Oracle 10g Express Edition, locally installedEdition, locally installed

• Oracle database schema is called "Oracle database schema is called "HRHR" "

• The password is "The password is "hrhr""

• Establishing a connection:Establishing a connection:

Connection dbCon = DriverManager.getConnection(Connection dbCon = DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521/xe","jdbc:oracle:thin:@localhost:1521/xe", "HR","HR", "hr");"hr");

Page 13: Data Access with JDBC

Stage 3: Creating StatementStage 3: Creating Statement

• A A StatementStatement object sends the SQL object sends the SQL commands to the DBMScommands to the DBMS

• executeQuery()executeQuery() is used for is used for SELECTSELECT statementsstatements

• executeUpdate()executeUpdate() is used for statements that is used for statements that create/modify tables create/modify tables

• An instance of active An instance of active ConnectionConnection is used to is used to create a create a StatementStatement object objectConnection dbCon = DriverManager.getConnection(Connection dbCon = DriverManager.getConnection( "jdbc:odbc:Library", "admin", "secret");"jdbc:odbc:Library", "admin", "secret");Statement stmt = Statement stmt = dbCon.createStatement()dbCon.createStatement();;

Page 14: Data Access with JDBC

Stage 4: Executing QueryStage 4: Executing Query

• executeQuery()executeQuery() executes SQL command executes SQL command through a previously created statementthrough a previously created statement

• Returns the results in a Returns the results in a ResultSetResultSet object object

Connection dbCon =Connection dbCon = DriverManager.getConnection(DriverManager.getConnection( "jdbc:odbc:Library", "admin", "secret");"jdbc:odbc:Library", "admin", "secret");

Statement stmt = dbCon.createStatement();Statement stmt = dbCon.createStatement();

ResultSet rs = ResultSet rs = stmt.executeQuerystmt.executeQuery(( "SELECT first_name FROM employees");"SELECT first_name FROM employees");

Page 15: Data Access with JDBC

Stage 4: Executing StatementStage 4: Executing Statement

• executeUpdate()executeUpdate() is used to submit is used to submit DML/DDL SQL statementsDML/DDL SQL statements

• DML is used to manipulate existing data DML is used to manipulate existing data in objects (using in objects (using UPDATEUPDATE, , INSERTINSERT, , DELETEDELETE statements) statements)

• DDL is used to manipulate database DDL is used to manipulate database objects (objects (CREATECREATE, , ALTERALTER, , DROPDROP))

Statement stmt = dbCon.createStatement();Statement stmt = dbCon.createStatement();int rowsAffected = int rowsAffected = stmt.executeUpdatestmt.executeUpdate(( "UPDATE employees SET salary = salary*1.2");"UPDATE employees SET salary = salary*1.2");

Page 16: Data Access with JDBC

Stage 5: Process The Returned Stage 5: Process The Returned ResultsResults

• The The ResultSetResultSet object object

• Maintains a cursor pointing to its current row Maintains a cursor pointing to its current row of dataof data

• Provides methods to retrieve column valuesProvides methods to retrieve column values

ResultSetResultSet rs = stmt.executeQuery( rs = stmt.executeQuery( "SELECT last_name, salary FROM employees");"SELECT last_name, salary FROM employees");while (rswhile (rs.next().next()) {) { String name = rsString name = rs.getString.getString("last_name");("last_name"); double salary = rsdouble salary = rs.getDouble.getDouble("salary");("salary"); System.out.println(name + " " + salary);System.out.println(name + " " + salary);}}

Page 17: Data Access with JDBC

Stage 6: Closing the Stage 6: Closing the ConnectionConnection

• Explicitly close a Explicitly close a ConnectionConnection, , StatementStatement, , and and ResultSetResultSet to release resources that are to release resources that are no longer neededno longer needed

try {try { Connection conn = ...; Connection conn = ...; Statement stmt = ...;Statement stmt = ...; ResultSet rset = stmt.executeQuery(ResultSet rset = stmt.executeQuery(...);...); ... ...} finally} finally // clean up// clean up rset.close(); rset.close(); stmt.close(); stmt.close(); conn.close();conn.close();}}

Page 18: Data Access with JDBC

SQLExceptionSQLException

• SQL statements can throw SQL statements can throw java.sqljava.sql. . SQLExceptionSQLException during their execution during their execution

try {try { rset = stmt.executeQuery(rset = stmt.executeQuery( "SELECT first_name, last_name FROM employee");"SELECT first_name, last_name FROM employee"); } catch (SQLException sqlex) {} catch (SQLException sqlex) {

... // Handle SQL errors here... // Handle SQL errors here } finally {} finally { // Clean up all used resources// Clean up all used resources try {try { if (rset != null) rset.close(); if (rset != null) rset.close(); } catch (SQLException sqlex) { } catch (SQLException sqlex) { ... // Ignore closing errors... // Ignore closing errors }} ......}}

Page 19: Data Access with JDBC

Querying Oracle Querying Oracle through JDBCthrough JDBC

Live DemoLive Demo

Page 20: Data Access with JDBC

JDBC StatementsJDBC StatementsStatementStatement, , PreparedStatementPreparedStatement and and

CallableStatementCallableStatement Interfaces Interfaces

Page 21: Data Access with JDBC

Submitting DML Statements Submitting DML Statements That Change the DatabaseThat Change the Database

1.1. Create an empty statement object:Create an empty statement object:

2.2. Use Use executeUpdate()executeUpdate() to execute the to execute the statement:statement:

• Example:Example:

Statement stmt = conn.createStatement();Statement stmt = conn.createStatement();

int count = stmt.executeUpdate(sql_dml_statement);int count = stmt.executeUpdate(sql_dml_statement);

Statement stmt = conn.createStatement();Statement stmt = conn.createStatement();

int rowsDeleted = stmt.executeUpdate("DELETE FROM int rowsDeleted = stmt.executeUpdate("DELETE FROM order_items WHERE order_id = 2354");order_items WHERE order_id = 2354");

Page 22: Data Access with JDBC

Submitting DDL StatementsSubmitting DDL Statements

1.1. Create an empty statement object:Create an empty statement object:

2.2. Use Use executeUpdate()executeUpdate() to execute the to execute the statement:statement:

• Example:Example:

Statement stmt = conn.createStatement();Statement stmt = conn.createStatement();

int count = stmt.executeUpdate(sql_int count = stmt.executeUpdate(sql_ddlddl_statement);_statement);

Statement stmt = conn.createStatement();Statement stmt = conn.createStatement();

stmt.executeUpdatstmt.executeUpdatee("("CREATE TABLE CREATE TABLE temp(col1 NUMBER(5,2), col2 VARCHAR2(30))temp(col1 NUMBER(5,2), col2 VARCHAR2(30))");");

Page 23: Data Access with JDBC

Unknown StatementsUnknown Statements

1.1. Create an empty statement objectCreate an empty statement object

2.2. Use Use execute()execute() to execute the statement to execute the statement

3.3. Process the statement accordinglyProcess the statement accordingly

Statement stmt = conn.createStatement();Statement stmt = conn.createStatement();

boolean result = stmt.execute(SQLstatement); boolean result = stmt.execute(SQLstatement);

if (result) {if (result) { // was a query - process results// was a query - process results ResultSet r = stmt.getResultSet(); ...ResultSet r = stmt.getResultSet(); ...}}else { // was an update or DDL - process resultelse { // was an update or DDL - process result int count = stmt.getUpdateCount(); ...int count = stmt.getUpdateCount(); ...}}

Page 24: Data Access with JDBC

Prepared StatementPrepared Statementss

• PreparedStatementPreparedStatement is used to is used to

• Execute a statement that takes Execute a statement that takes parametersparameters

• Execute given statement many timesExecute given statement many times

String insertString insertSQLSQL = "INSERT INTO employees(" + = "INSERT INTO employees(" + "first_name, last_name, salary) VALUES(?,?,?)";"first_name, last_name, salary) VALUES(?,?,?)";PreparedStatement stmt =PreparedStatement stmt = ccon.prepareStatement(inserton.prepareStatement(insertSQLSQL););stmt.setString(stmt.setString(11,, "Svetlin" "Svetlin"););stmt.setString(stmt.setString(22,, "Nakov" "Nakov"););stmt.setstmt.setDoubleDouble(3,(3, 25000.0 25000.0););stmt.executeUpdate();stmt.executeUpdate();

Page 25: Data Access with JDBC

Retrieving Auto Generated Retrieving Auto Generated Primary KeyPrimary Key

• Some databases support "auto increment" Some databases support "auto increment" primary key columnsprimary key columns• E. g. MS SQL Server, MS Access, MySQL, ...E. g. MS SQL Server, MS Access, MySQL, ...

• JDBC can retrieve auto generated keysJDBC can retrieve auto generated keys

// Insert row and return PK// Insert row and return PKint rowCount = stmt.executeUpdate(int rowCount = stmt.executeUpdate( "INSERT INTO Messages(Msg) VALUES ('Test')","INSERT INTO Messages(Msg) VALUES ('Test')", Statement.RETURN_GENERATED_KEYS);Statement.RETURN_GENERATED_KEYS);

// // Get the auto generated Get the auto generated PKPKResultSet rs = stmt.getGeneratedKeys();ResultSet rs = stmt.getGeneratedKeys();rs.next();rs.next();long primaryKey = rs.getLong(1);long primaryKey = rs.getLong(1);

Page 26: Data Access with JDBC

Retrieving Auto Generated Retrieving Auto Generated Primary Key in OraclePrimary Key in Oracle

• Oracle does not support "auto increment" Oracle does not support "auto increment" primary keyprimary key

• Use sequences to generate unique valuesUse sequences to generate unique values

stmtSeq = dbCon.createStatement();stmtSeq = dbCon.createStatement();rsNextId = stmtSeq.executeQuery(rsNextId = stmtSeq.executeQuery( "SELECT <some_sequence>.nextval FROM dual");"SELECT <some_sequence>.nextval FROM dual");rsNextId.next();rsNextId.next();long nextId = rsNextId.getLong(1); long nextId = rsNextId.getLong(1);

psIns = dbCon.prepareStatement(psIns = dbCon.prepareStatement( "INSERT INTO Table(id, ...) VALUES(?, ?)");"INSERT INTO Table(id, ...) VALUES(?, ?)");psIns.setLong(1, nextId);psIns.setLong(1, nextId);psIns.setString(2, ...);psIns.setString(2, ...);psIns.executeUpdate();psIns.executeUpdate();

Page 27: Data Access with JDBC

Callable StatementCallable Statementss

• CallableStatementCallableStatement interface: interface:• Is used for executing stored proceduresIs used for executing stored procedures

• Can pass input parametersCan pass input parameters

• Can retrieve output parametersCan retrieve output parameters

• Example:Example:

CallableStatement callStmt =CallableStatement callStmt = dbCon.prepareCall("call SP_Insert_Msg(?,?)");dbCon.prepareCall("call SP_Insert_Msg(?,?)");callStmt.setString(1, msgText);callStmt.setString(1, msgText);callStmt.registerOutParameter(2, Types.BIGINT);callStmt.registerOutParameter(2, Types.BIGINT);callStmt.executeUpdate();callStmt.executeUpdate();long id = callStmt.getLong(2);long id = callStmt.getLong(2);

Page 28: Data Access with JDBC

JDBC StatementsJDBC StatementsLive DemoLive Demo

Page 29: Data Access with JDBC

Transactions Transactions Management in JDBCManagement in JDBC

Page 30: Data Access with JDBC

DataDatabase Transactionsbase Transactions

• A A database transactiondatabase transaction is a set of database is a set of database operations that must be either entirely operations that must be either entirely completed or abortedcompleted or aborted

• A simple transaction is usually in this form:A simple transaction is usually in this form:

1.1.Begin the transactionBegin the transaction

2.2.Execute several SQL DML statementsExecute several SQL DML statements

3.3.Commit the transactionCommit the transaction

• If one of the SQL statements fails, rollback If one of the SQL statements fails, rollback the entire transactionthe entire transaction

Page 31: Data Access with JDBC

JDBCJDBC Transactions Transactions

• JDBC transaction mode:JDBC transaction mode:

• Auto-commitAuto-commit by default by default

• Can be turned off by calling Can be turned off by calling setAutoCommit(false)setAutoCommit(false)

• In auto-commit mode each statement is In auto-commit mode each statement is treated as a separate transactiontreated as a separate transaction

• If the auto-commit mode is off, no changes If the auto-commit mode is off, no changes will be committed until will be committed until commit()commit() is invoked is invoked

• Auto-commit mode can be turned back on by Auto-commit mode can be turned back on by calling calling setAutoCommit(truesetAutoCommit(true))

Page 32: Data Access with JDBC

JDBC Transactions –ExampleJDBC Transactions –Example

• If we don’t want certain changes to be made If we don’t want certain changes to be made permanent, we can issue permanent, we can issue rollbackrollback()()

dbCon.setAutoCommit(false);dbCon.setAutoCommit(false);try {try { Statement stmt = con.createStatement();Statement stmt = con.createStatement(); stmt.executeUpdate("INSERT INTO Groupsstmt.executeUpdate("INSERT INTO Groups " +" + "VALUES"VALUES (101, '(101, 'AdministratorsAdministrators')");')"); stmt.executeUpdate("INSERT INTO Users " +stmt.executeUpdate("INSERT INTO Users " + "VALUES (NULL, 'Mary', 101)");"VALUES (NULL, 'Mary', 101)"); dbCon.commit();dbCon.commit();} catch (Exception ex) {} catch (Exception ex) { dbCon.rollback();dbCon.rollback(); throw ex;throw ex;}}

Page 33: Data Access with JDBC

TransactionsTransactionsin JDBCin JDBC

Live DemoLive Demo

Page 34: Data Access with JDBC

JDBC Advanced JDBC Advanced Features and Best Features and Best

PracticesPractices

Page 35: Data Access with JDBC

Database Specific PropertiesDatabase Specific Properties

• You can pass database specific You can pass database specific information to the database by using information to the database by using Properties objectProperties object

• Example for Oracle database:Example for Oracle database:

Properties props = new java.util.Properties();Properties props = new java.util.Properties();

props.put("user", "scott");props.put("user", "scott");props.put("password", "tiger");props.put("password", "tiger");props.put("defaultRowPrefetch", "30");props.put("defaultRowPrefetch", "30");props.put("defaultBatchValue", "5");props.put("defaultBatchValue", "5");

Connection dbCon = DriverManger.getConnection(Connection dbCon = DriverManger.getConnection( "jdbc:oracle:thin:@hoststring", props); "jdbc:oracle:thin:@hoststring", props);

Page 36: Data Access with JDBC

Connection PoolConnection Pool

• Connection pool contains a number of Connection pool contains a number of open database connectionsopen database connections

• There are a few choices when using There are a few choices when using connection pool:connection pool:

1.1. Depend on the application server Depend on the application server

2.2. Use JDBC 2.0 interfaces Use JDBC 2.0 interfaces ((ConnectionPoolDataSourceConnectionPoolDataSource and and PooledConnectionPooledConnection))

3.3. Create your own connection pool Create your own connection pool

Page 37: Data Access with JDBC

Optimal Isolation LevelOptimal Isolation Level

• You can set the transaction isolation level by You can set the transaction isolation level by calling calling setTransactionIsolation(setTransactionIsolation(levellevel))

Transaction LevelPermitted Phenomena

ImpactDirty

ReadsNon-Repeatable

ReadsPhantom

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

Page 38: Data Access with JDBC

ResultSet MetadataResultSet Metadata

• ResultSetMetaDataResultSetMetaData class class

• Used to get information about the types Used to get information about the types and properties of the columns in a and properties of the columns in a ResultSetResultSet object object

ResultSet rs = stmt.executeQuery(ResultSet rs = stmt.executeQuery( "SELECT "SELECT ** FROM employees"); FROM employees");ResultSetMetaData rsm = rs.getMetaData();ResultSetMetaData rsm = rs.getMetaData();int number = rsm.getColumnCount();int number = rsm.getColumnCount();ffor (int i=0; i<number;or (int i=0; i<number; i++)i++) { { System.out.println(rsm.getColumnName(i));System.out.println(rsm.getColumnName(i));}}

Page 39: Data Access with JDBC

Close Unneeded ResourcesClose Unneeded Resources

• Closing connections, statements and result Closing connections, statements and result sets explicitly allows garbage collector to sets explicitly allows garbage collector to recollect memory and free resources as recollect memory and free resources as early as possibleearly as possible

• Close statement object as soon as you Close statement object as soon as you finish working with themfinish working with them

• Use Use try-finallytry-finally statement to guarantee statement to guarantee that resources will be freed even in case of that resources will be freed even in case of exceptionexception

Page 40: Data Access with JDBC

Choose the Right StatementChoose the Right Statement

• Use Use PreparedStatementPreparedStatement when you when you execute the same statement more than execute the same statement more than onceonce

• Use Use CallableStatementCallableStatement when you want when you want result from multiple and complex result from multiple and complex statements for a single requeststatements for a single request

Page 41: Data Access with JDBC

Use Batch Updates/RetrievalUse Batch Updates/Retrieval

• Send multiple queries to reduce the number Send multiple queries to reduce the number of JDBC calls and improve performance:of JDBC calls and improve performance:

• You can improve performance by increasing You can improve performance by increasing number of rows to be fetched at a timenumber of rows to be fetched at a time

statement.addBatch("sql_query1");statement.addBatch("sql_query1");statement.addBatch("sql_query2");statement.addBatch("sql_query2");statement.addBatch("sql_query3");statement.addBatch("sql_query3");

statement.executeBatch();statement.executeBatch();

sstatement.setFetchSize(30);tatement.setFetchSize(30);

Page 42: Data Access with JDBC

Optimize the SQL QueriesOptimize the SQL Queries

• Bad:Bad:

• Good:Good:

Statement stmt = con.createStatement();Statement stmt = con.createStatement();

ResultSet rs = stmt.executeQuery(ResultSet rs = stmt.executeQuery( ""SELECTSELECT * * FROMFROM EMPLOYEEEMPLOYEE WHEREWHERE IDID==11");");

Statement stmt = con.createStatement();Statement stmt = con.createStatement();

ResultSet rs = stmt.executeQuery(ResultSet rs = stmt.executeQuery( ""SELECTSELECT SALARYSALARY FROMFROM EMPLOYEEEMPLOYEE WHEREWHERE ID=1ID=1");");

Page 43: Data Access with JDBC

ProblemsProblems

1.1. Write a program that prints the names of all Write a program that prints the names of all employees and their salaries from the standard employees and their salaries from the standard HR schema in Oracle 10g. Don't forget to HR schema in Oracle 10g. Don't forget to ensure that all exceptions are handled ensure that all exceptions are handled appropriately and used resources are cleaned.appropriately and used resources are cleaned.

2.2. Write a program that reads a last name and a Write a program that reads a last name and a salary range from the console and prints all salary range from the console and prints all matched employees and their salaries from the matched employees and their salaries from the standard HR schema in Oracle 10g. Use standard HR schema in Oracle 10g. Use PreparedStatementPreparedStatement with parameters. Handle with parameters. Handle the possible exceptions and close all used the possible exceptions and close all used resources.resources.

Page 44: Data Access with JDBC

Problems (2)Problems (2)

3.3. Write a program that creates a table Write a program that creates a table Countries(country_id, country_name)Countries(country_id, country_name) and a sequence and a sequence SEQ_CountriesSEQ_Countries. Define a class . Define a class CountryCountry with the same fields like the columns with the same fields like the columns in the in the CountriesCountries table. Write a method to table. Write a method to insert new country. Write a method to list all insert new country. Write a method to list all countries (it should return countries (it should return Country[]Country[]). Write a ). Write a method to find country by method to find country by country_idcountry_id. Write a . Write a method to find country by part of its name. method to find country by part of its name. Finally write a method to drop the Finally write a method to drop the CountriesCountries table and the sequence table and the sequence SEQ_CountriesSEQ_Countries. Test . Test all methods.all methods.

Page 45: Data Access with JDBC

Problems (3)Problems (3)

4.4. Create tables Create tables Persons(person_id, Persons(person_id, person_name)person_name),, Accounts(account_id, Accounts(account_id, acc_holder_idacc_holder_id,amount,amount)) and and Log(log_id,Log(log_id, msg_date, log_msg)msg_date, log_msg).. Define sequences for Define sequences for populating the primary keys in these tables populating the primary keys in these tables (without triggers).(without triggers).

Write stored procedures for inserting persons, Write stored procedures for inserting persons, accounts and log messages and Java methods accounts and log messages and Java methods that call them.that call them.

Write method for transferring funds between Write method for transferring funds between accounts. It should keep track of all successful accounts. It should keep track of all successful transfers in the transfers in the LogLog table. Use transactions to table. Use transactions to maintain data consistency.maintain data consistency.

Page 46: Data Access with JDBC

HomeworkHomework

1.1. Write a program that prints the names of all Write a program that prints the names of all employees, their managers and departments employees, their managers and departments from the standard HR schema in Oracle 10g. from the standard HR schema in Oracle 10g. Handle the possible exceptions and close all Handle the possible exceptions and close all used resources.used resources.

2.2. Write a program that reads a department name Write a program that reads a department name from the console and prints all employees in from the console and prints all employees in this department and their average salary. Use this department and their average salary. Use the standard HR schema in Oracle 10g. Use the standard HR schema in Oracle 10g. Use PreparedStatementPreparedStatement with parameters. Handle with parameters. Handle the possible exceptions and close all used the possible exceptions and close all used resources.resources.

Page 47: Data Access with JDBC

Homework (2)Homework (2)

3.3. Write a program that creates tables Write a program that creates tables Users(user_id, user_name, group_id)Users(user_id, user_name, group_id) and and Groups(group_id, group_name)Groups(group_id, group_name) along along with sequences fro populating their primary with sequences fro populating their primary keys. Write classes keys. Write classes UserUser and and GroupGroup that that correspond to these tables. Write methods for correspond to these tables. Write methods for adding new users and groups. Write methods adding new users and groups. Write methods for listing all groups, all users and all users by for listing all groups, all users and all users by given group. Write methods for updating and given group. Write methods for updating and deleting users and groups. Finally write a deleting users and groups. Finally write a method to drop the tables method to drop the tables UsersUsers and and GroupsGroups and their sequences. Test all these methods. and their sequences. Test all these methods. Handle the exceptions appropriately and close Handle the exceptions appropriately and close all used resources.all used resources.

Page 48: Data Access with JDBC

Homework (3)Homework (3)

4.4. Modify the previous program to add also the Modify the previous program to add also the table table Log(log_id, msg_date, msg_text)Log(log_id, msg_date, msg_text) that keeps track of all changes in the all other that keeps track of all changes in the all other tables. Modify all methods to maintain the log. tables. Modify all methods to maintain the log. Don't forget to use transactions if a business Don't forget to use transactions if a business operation modifies several tables.operation modifies several tables.

Add a method for adding user and group in the Add a method for adding user and group in the same time (by given user name and group same time (by given user name and group name). If the group does not exists, it should be name). If the group does not exists, it should be created on demand. Use transactions to created on demand. Use transactions to guarantee the data consistency. Don't forget to guarantee the data consistency. Don't forget to register the operations in the logs.register the operations in the logs.