Data Access with JDBC

  • 4,027 views
Uploaded on

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

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

More in: Education
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Be the first to comment
No Downloads

Views

Total Views
4,027
On Slideshare
0
From Embeds
0
Number of Embeds
3

Actions

Shares
Downloads
240
Comments
0
Likes
2

Embeds 0

No embeds

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
    No notes for slide
  • (c) 2007 National Academy for Software Development - http://academy.devbg.org All rights reserved. Unauthorized copying or re-distribution is strictly prohibited.* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 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("sun.jdbc.odbc.JdbcOdbcDriver");
  • * 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 .
  • * 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.
  • * 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.
  • * 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 .
  • * 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.
  • * 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.
  • * 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.
  • * 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
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 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.
  • * 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.
  • * 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.
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ## Prepared statements can execute select SQL statements also: String query ="SELECT Name from CS4400 where SSN=?"; PreparedStatement stmt = con.prepareStatement(query); stmt.setInt(1,SSN); ResultSet rs = stmt.executeUpdate(); while (rs.next()) System.out.println(rs.getString(Name);
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 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.
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 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.
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 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.
  • * 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.
  • * 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'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't have to bother much about that insertion. Obviously this improves performance significantly.
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 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)
  • * 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.
  • * 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()
  • * 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.
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##
  • * 07/16/96 (c) 2006 National Academy for Software Development - http://academy.devbg.org* ##

Transcript

  • 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
  • 3. JDBC Technology Overview
  • 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);
  • 28. JDBC Statements Live Demo
  • 29. Transactions Management in JDBC
  • 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.