Unit 5-jdbc2

86
JDBC

description

java

Transcript of Unit 5-jdbc2

  • 1.JDBC

2.

  • JDBCis Java API twhichallows the Java programmers to access database management system from Java code.
  • It is a java API which enables the java programs to execute SQL statements.
  • Defines how a java programmer can access the database in tabular format from Java code using a set of standard interfaces and classes written in the Java programming language.
  • JDBC provides methods for querying and updating the data in Relational Database Management system such as SQL, Oracle etc

3. JDBC Driver Types

  • Type 1 JDBC-to-ODBC Driver.
  • Type 2 Java/NativeCodeDriver.
  • Type 3 JDBCDriver.
  • Type 4JDBC Driver.

4.

  • Type 1JDBC-to-ODBC Driver The JDBC type 1 driver, also known as the JDBC-ODBC bridge is a database driver implementation that employs the ODBC driver to connect to the database.
  • The driver converts JDBC method calls into ODBC function calls.
  • The driver is implemented in thesun.jdbc.odbc.JdbcOdbcDriverclass and comes with the Java 2 SDK, Standard Edition.
  • The driver is platform-dependent as it makes use of ODBC which in turn depends on native libraries of the operating system. Also, using this driver has got other dependencies such as ODBC must be installed on the computer having the driver and thedatabase which is being connected to must support an ODBC driver.
  • Type 1 is the simplest of all but platform specific i.e only to Microsoft platform.
  • Type 1 drivers are "bridge" drivers. They use another technology such as Open Database Connectivity (ODBC) to communicate with a database. This is an advantage because ODBC drivers exist for many Relational Database Management System (RDBMS)platforms.+ A Type 1 driver needs to have the bridge driver installed and configured before JDBC can be used with it. This can be aserious drawback for a production application.

5.

  • Functions:
  • Translates query obtained by JDBC into corresponding ODBC query, which is then handled by the ODBC driver.
  • Sun provides a JDBC-ODBC Bridge driver. sun.jdbc.odbc.JdbcOdbcDriver.
  • Client -> JDBC Driver -> ODBC Driver -> Database
  • There is some overhead associated with the translation work to go from JDBC to ODBC.
  • Advantages: Almost any database for which ODBC driver is installed, can be accessed.
  • Disadvantages:
  • Performance overhead since the calls have to go through the JDBC overhead bridge to the ODBC driver, then to thenative database connectivity interface.
  • The ODBC driver needs to be installed on the client machine.

6. Type 1 JDBC Driver 7. Type 2 Java/Native Code Driver

  • The JDBC type 2 driver, also known as the Native-API driver is a database driver implementation that uses the client-sidelibraries of the database.
  • The driver converts JDBC method calls into native calls of the database API.
  • A native-API partly Java technology-enabled driver converts JDBC calls into calls on the client API for Oracle, Sybase, Informix, DB2, or other DBMS.
  • Type 2 drivers use a native API to communicate with a database system.

8.

  • Functions:
  • This type of driver converts JDBC calls into calls to the client API for that database.
  • Client -> JDBC Driver -> Vendor Client DB Library -> Database
  • Advantage Better performance than Type 1 since no jdbc to odbc translation is needed.
  • Disadvantages
  • The vendor client library needs to be installed on the client machine.
  • Not all databases give the client side library.

9. Type 2 JDBC Driver 10.

  • The JDBC type 3 driver, also known as the network-protocol driver is a database driver implementation which makes use of amiddle-tier between the calling program and the database.
  • The middle-tier (application server) converts JDBC calls directlyor indirectly into the vendor-specific database protocol.
  • The same driver can be used for multiple databases. It depends on the number of databases the middleware has been configured to support.
  • Making use of the middleware provides additional advantages of security and firewall access.
  • A net-protocol fully Java technology-enabled driver translates JDBC API calls into a DBMS-independent net protocolwhich is then translated to a DBMS protocol by a server.

Type 3 JDBC Driver 11.

  • Functions:
  • Follows a three tier communication approach.
  • Can interface to multiple databases - Not vendor specific.
  • The JDBC Client driver written in java, communicates with a middleware-net-server using a database independent protocol, and then this net server translates this request into database commands for that database.
  • Thus the client driver to middleware communication is database independent.
  • Client -> JDBC Driver -> Middleware-Net Server -> Any Database
  • Advantages
  • Since the communication between client and the middleware server is database independent, there is no need for thevendor db library on the client machine. Also the client to middleware need'nt be changed for a new database.
  • eg.Weblogic.
  • At client side a single driver can handle any database.(It works provided the middlware supports that database)
  • Disadvantages
  • Requires database-specific coding to be done in the middle tier.
  • An extra layer added may result in a time-bottleneck. But typically this is overcome by providing efficient middleware

12. Type 3 JDBC Driver 13. Type 4 JDBC Driver

  • The JDBC type 4 driver, also known as the native-protocol driver is a database driver implementation that converts JDBCcalls directly into the vendor-specific database protocol.
  • The type 4 driver is written completely in Java and is hence platform independent.
  • Since many of these protocols are proprietary the database vendors themselves will be the primary sourcefor this style of driver.

14.

  • Functions
  • Type 4 drivers are entirely written in Java that communicate directly with a vendor's database.No translation or middleware layers, are required, improving performance.
  • The driver converts JDBC calls into the vendor-specific database protocol so that client applications can communicate directly with the database server.
  • Completely implemented in Java to achieve platform independence.
  • e.g include the widely used Oracle thin driver - oracle.jdbc.driver. OracleDriver which connect to jdbc:oracle:thinURL format.
  • Client Machine -> Native protocol JDBC Driver -> Database server
  • Advantages These drivers don't translate the requests into db request to ODBC or pass it to client api for the db, nor do theyneed a middleware layer for request indirection. Thus the performance is considerably improved.
  • Disadvantage At client side, a separate driver is needed for each database.

15. Type 4 JDBC Driver 16. JDBC Drivers JDBC Type I Bridge Type II Native Type III Middleware Type IV Pure ODBC ODBC Driver .lib Middleware Server 17. Brief Overview of the JDBC Process

  • Loading the JDBC driver
  • Connecting to the DBMS
  • Creating and executing a statement.
  • Processing data returned by the DBMS
  • Terminating the connection with the DBMS

18. Loading the JDBC driver

  • The JDBC driver must be loaded before connect to the DBMS.
  • The driver is loaded by calling the Class.forName() method and passing it the name of
  • the driver.
  • Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

19. Connecting to the DBMS

  • Once the driver is loaded,connect to the DBMS usingmethod
  • DriverManager.getConnection()
  • The DriverManager.getConnection() method is passed theURL of the database, and the userID and password if
  • required by the DBMS.
  • The URL is a String object that containsthe driver name and the name of the databasethat is being accessed.
  • The DriverManager.getConnection() method returns aConnection interfacethat isusedthroughout the process
  • to reference the database.

20.

  • String url =jdbc:odbc:CustomerInformation;
  • String userID=sjec;
  • String password = comp
  • try
  • {
  • Class.forName(sun.jdbc.odbc.JdbcOdbcDrive);
  • Connectionconn = DriverManager.getConnection(url,userID,password);
  • }

21. Creating and executing a statement.

  • Thecon.createStatement()method is used to create a statementobject.
  • The statement object is thenused to execute a query and return a resultset object that contains the response from the
  • DBMS.
  • Statement stmt;
  • ResultSetrs;
  • Try
  • {
  • String query = SELECT * FROM customers;
  • stmt = con.createStatement();
  • rs = stmt.executeQuery(query);
  • con.close();
  • }

22. Processing data returned by the DBMS

  • Thejava.sql.ResultSetobject is assigned the results received from the DBMS after the
  • query is processed.
  • The java.sql.ResultSet object consists of methods used to interact with data.
  • ResultSet rs;
  • String FirstName;
  • String LastName;
  • while(rs.next());
  • {
  • FirstName = rs.getString(FirstName);
  • LastName= rs.getString(LastName);
  • System.out.println(FirstName++LastName);
  • }

23. Terminating the connection with the DBMS

  • The connection to the DBMS is terminated by using close() method of the Connection object once finished
  • accessing the DBMS.
  • con.close();

24. JDBC Architecture Java Application JDBC Driver Manager (T2) Java Portion (T1) JDBC- ODBC Bridge (T4) Java Driver to vendor's protocol ODBC Driver Proprietary, vendor-specific database access protocol Provided with Sun's JDK JDBC Drivers Native Portion (T3) JavaClient Server Component 25. Database Connection

  • Beforethe connection is made, the JDBC driver must be loaded and registered with the DriverManager.
  • The purpose of loading and registering the JDBC driver is to bring the JDBC driver into the JVM. The JDBC driver
  • is automatically registered with the DriverManager once theJDBC driver is loaded and is therefore available to the
  • JVM and can be used.
  • The Class.forName() methods throws a ClassNotFoundException.
  • try
  • {
  • Class.forName(sun.jdbc.odbc.JdbcOdbcDrive);
  • }
  • catch(ClassNotFoundException error)
  • {
  • System.out.println(Unable to load JDBC/ODBC bridge+error.getMessage());
  • }

26. The Connection

  • After the JDBC driver is successfully loaded and registered,connect to thedatabase.
  • AConnectionobject represents a connection with a database. When we connect to a database by using connection method, we create a Connection Object, which represents the connection to the database.
  • The datasource that the JDBC component will connect to is defined using the URL format. The URL consist of 3 parts. These are
  • jdbc which indicates that the JDBC protocol is to be used to read the URL.
  • which is theJDBc driver name.
  • which is the name of the database.
  • ex:Stringurl = jdbc:odbc:sjec;

27.

  • The connection to the databse is established by using one of the 3 getConnection method.
  • getConnection(String url)
  • getConnection(String url,String id,String password);
  • getConnection(String url, Properties prop);
  • Ex:getConnection(jdbc:odbc:sjec, cse, sem7);

28.

  • The getConnection() method request access to the database from the DBMS. It is up to the DBMS to grant or reject access.
  • A connection object is returned by thegetConnection() method if access is granted.
  • otherwise getConnection() method throws a SQLException.
  • Sometimes the DBMS grants access to a database to anyone.
  • In this casegetConnection(String url) method is used.

29.

  • Stringurl = jdbc:odbc:sjec;
  • try
  • {
  • Class.forName(sun.jdbc.odbc.JdbcOdbcDrive);
  • conn = DriverManager.getConnection(url)
  • }
  • catch(ClassNotFoundException error)
  • {
  • System.out.println(Unable to load JDBC/ODBC bridge+error.getMessage());
  • }
  • catch(SQLException error)
  • {
  • System.out.println(can not connect to the datanase+error.getMessage());
  • }

30.

  • Some databases limit access to authorized users andrequire to supply a userID
  • and password .

31.

  • String url =jdbc:odbc:CustomerInformation;
  • String userID=sjec;
  • String password = comp
  • Private Connection conn;
  • try
  • {
  • Class.forName(sun.jdbc.odbc.JdbcOdbcDrive);
  • conn = DriverManager.getConnection(url,userID,password);
  • }
  • catch(ClassNotFoundException error)
  • {
  • System.out.println(Unable to load JDBC/ODBC bridge+error.getMessage());
  • }
  • catch(SQLException error
  • {
  • System.out.println(can not connect to the datanase+error.getMessage());
  • }

32.

  • Some DBMS requires additional information.
  • This additional information is referred to as properties and must beassociated with a
  • Propertiesobject, which is passed to the DBMS as a getConnection() parameter.

33.

  • Connection con ;
  • Properties props = new Properties();
  • try
  • {
  • FileInputStreamfis = new FileInputStream(DBProps.txt);
  • props.load(fis);
  • }
  • catch(IOException err)
  • {
  • System.out.println(error loading property file);
  • }
  • try
  • {
  • Class.forName(sun.jdbc.odbc.JdbcOdbcDrive);
  • conn = DriverManager.getConnection(url,props);
  • }
  • catch(ClassNotFoundExceptionerror)
  • {
  • System.out.println(Unable to load JDBC/ODBC bridge+error.getMessage());
  • }
  • catch(SQLException error)
  • {
  • System.out.println(can not connect to the datanase+error.getMessage());
  • }

34. Associating the JDBC/ODBC bridge with the Database

  • select start | settings | control panel
  • select ODBC 32 to display the ODBC DataSourceAdministrator
  • Add new user by selecting the add button
  • select the driver and then finish
  • Enter the name of the datasourcename
  • .
  • .
  • ..
  • ..

35. Associating the JDBC/ODBC bridge with the Database

  • 1.Make sure you have the Access 95 ODBC drivers installed. These ODBC drivers can be installed from theAccess install program.
  • 2.Select Start Menu|Settings|Control Panels.
  • 3.Click on 32 bit ODBC.
  • 4.Click on the Add button and choose the Access Driver.
  • 5.Type in a Data Source Name and Description (anything you like).
  • 6.In the Database area, click on Select.
  • 7.Select the Access database file; a sample database is located in MSofficeACCESSSamples (if you installed it during the Access installation). However, you can specify any Access database you want.
  • 8.You may want to click on the Advanced button and set the Username and Password. Click on OK and then on Close to complete the configuration

36. Statement Objects

  • Once a connection to the database is opened, thencreateand sends a
  • query to access data contained in the database. The query is written SQL.
  • One of the 3 types of Statement objects is used to execute the query.
  • Statemen t which executes a query immediately.
  • PrepapedStatementwhich is used to execute a compiled query
  • CallableStatement , which is used to execute store procedures .

37. The Statement Object

  • 3 methods
  • executeQuery();
  • executeUpdate();method is usedto execute queries that contain UPDATE andDELETE SQL statement.
  • execute();method is used when there may be multiple results returned.

38.

  • String url =jdbc:odbc:CustomerInformation;
  • String userID=sjec;
  • String password = comp
  • Private Connection conn;
  • try
  • {
  • Class.forName(sun.jdbc.odbc.JdbcOdbcDrive);
  • conn = DriverManager.getConnection(url,userID,password);
  • }
  • catch(ClassNotFoundException error)
  • {
  • System.out.println(Unable to load JDBC/ODBC bridge+error.getMessage());
  • }
  • catch(SQLException error)
  • {
  • System.out.println(can not connect to the datanase+error.getMessage());
  • }

39.

  • Statement stmt;
  • try
  • {
  • String query = SELECT * FROM customers;
  • stmt = con.createStatement();
  • rs = stmt.executeQuery(query);
  • con.close();
  • }
  • catch(SQLException error)
  • {
  • System.out.priintln( cannot connect to the database);
  • }

40. executeUpdate() 41.

  • String url =jdbc:odbc:CustomerInformation;
  • String userID=sjec;
  • String password = comp
  • Private Connection conn;
  • try
  • {
  • Class.forName(sun.jdbc.odbc.JdbcOdbcDrive);
  • conn = DriverManager.getConnection(url,userID,password);
  • }
  • catch(ClassNotFoundException error)
  • {
  • System.out.println(Unable to load JDBC/ODBC bridge+error.getMessage());
  • }
  • catch(SQLException error)
  • {
  • System.out.println(can not connect to the datanase+error.getMessage());
  • }

42.

  • try
  • {
  • String query = UPDATE customers set PAID =Twhere balance = 0;
  • stmt = con.createStatement();
  • rs = stmt.executeUpdate(query);
  • con.close();
  • }
  • catch(SQLException error)
  • {
  • System.out.priintln( cannot connect to the database);
  • }

43. PreparedStatement Object 44.

  • String url =jdbc:odbc:CustomerInformation;
  • String userID=sjec;
  • String password = comp
  • Private Connection conn;
  • try
  • {
  • Class.forName(sun.jdbc.odbc.JdbcOdbcDrive);
  • conn = DriverManager.getConnection(url,userID,password);
  • }
  • catch(ClassNotFoundException error)
  • {
  • System.out.println(Unable to load JDBC/ODBC bridge+error.getMessage());
  • }
  • catch(SQLException error)
  • {
  • System.out.println(can not connect to the datanase+error.getMessage());
  • }

45.

  • try
  • {
  • String query = SELECT * FROM customers WHERE CustNum = ?;
  • PreparedStatemnt ps = con.preparedStatement();
  • ps.setString(1,123);
  • rs = ps.executeQuery(query);
  • ps.close();
  • }
  • catch(SQLException error)
  • {
  • System.out.priintln( cannot connect to the database);
  • }

46. CallableStatement

  • The CallableStatement object is used to used to call a stored procedure.
  • The CallableStatement object uses 3 types of parameters when calling a stored procedure.
  • These parameters are IN, OUT and INOUT.
  • The IN parameter contain any data that needs to be passed to thestored procedure and whose valueis assigned using thesetxxx()method.
  • The OUT parametercontain the value returned by the stored procedure. The OUT parameter must be registered using theregisterOutParameter()and is retrieved bygetxxx()method.
  • The INOUT parameter is a single parameter is a single parameter is used to both pass information to the stored procedure and retrieve information from a stored procedure.
  • TheregisterOutParameter requires 2 parameter. The first parameter is the integer that represents the number of the parameter. The second parameter is the data type of the value returned by the stored procedure.

47.

  • String url =jdbc:odbc:CustomerInformation;
  • String userID=sjec;
  • String password = comp
  • Private Connection conn;
  • try
  • {
  • Class.forName(sun.jdbc.odbc.JdbcOdbcDrive);
  • conn = DriverManager.getConnection(url,userID,password);
  • }
  • catch(ClassNotFoundException error)
  • {
  • System.out.println(Unable to load JDBC/ODBC bridge+error.getMessage());
  • }
  • catch(SQLException error)
  • {
  • System.out.println(can not connect to the datanase+error.getMessage());
  • }

48.

  • try
  • {
  • String query = { CALL LastOrderNumber(?) } ;
  • CallableStatement cs = con.prepareCall(query);
  • cs.registerOutParameter(1, Types.VARCHAR);
  • csstatement.execute();
  • lastOrdrNumber = cs.getString();
  • cs.close()
  • }
  • catch(SQLException error)
  • {
  • System.out.println(SQL error+error);
  • }
  • con.close();

49. ResultSet

  • TheResultSet object contains methods that are used tocopy data from the Result into aJava
  • variable for further processing.
  • Data in a ResultSet objectis logically organized into a virtual table consisting of rowsand column.
  • Resultset object also contains metadata such ascolumn names, column size, and column data
  • types.
  • The ResultSet uses a virtual curser to point to a row of the virtual table.
  • Wemust move the virtualcurser to each row and use othermethods of theResultSet object to
  • interact with the data stored incolumns of that row.
  • The virtual curser is positioned above thefirst row of the data when the ResultSet isreturned by
  • the executeQuery() method. This means that virtual curser must be moved tothe first row using
  • next()method.

50.

  • The next() method returns a boolean true if the row contains a data. Otherwise, a boolean false isreturned indicating that no more rows existin the ResultSet.
  • Once the virtual curser points to a row, the getxxx() method is used to copy data from the row to a collection , object or variable.
  • The getxxx() parameterrequires one parameter, which isan integerthat represent he number of column that contains the data.
  • Ex: getInt(1);
  • getString(2);
  • getInt(3);

51.

  • String url =jdbc:odbc:CustomerInformation;
  • String userID=sjec;
  • String password = comp
  • Private Connection conn;
  • try
  • {
  • Class.forName(sun.jdbc.odbc.JdbcOdbcDrive);
  • conn = DriverManager.getConnection(url,userID,password);
  • }
  • catch(ClassNotFoundException error)
  • {
  • System.out.println(Unable to load JDBC/ODBC bridge+error.getMessage());
  • }
  • catch(SQLException error)
  • {
  • System.out.println(can not connect to the datanase+error.getMessage());
  • }

52.

  • try
  • { String query = SELECT FirstName,LastName FROM Customers;
  • stmt = con.createStatement();
  • rs = stmt.executeUpdate(query);
  • con.close();
  • }
  • catch(SQLException error)
  • {
  • System.out.priintln( cannot connect to the database);
  • }
  • try
  • {while(rs.next())
  • {
  • FirstName = rs.getString(1);
  • LastName= rs.getString(2);
  • System.out.println(FirstName++LastName);
  • }
  • }
  • Catch(SQLException error)
  • {System.out.println(data entry error);
  • }

53. Scrollable ResultSet

  • There are 6 methods of the ResultSet object that are used to position the virtual cluster.
  • next()
  • previous()
  • first()
  • last()
  • absolute()
  • relative()
  • getRow()
  • The absolute method positions the virtual curster atthe row specified by the integer
  • passed as a parameter to the absolute() method.
  • The relative() method moves the virtual curser thespecifiednumber of rows contained
  • in the parameter. The parameter is a positive or negative integer where the sign
  • represents the direction the virtual curser is moved.
  • getRow() method returns an integer that represents the number of current rows in the
  • ResultSet.

54.

  • The Statementobjectthat is created using the createStatement() of theConnection
  • object must be setup to handle a scrollable ResultSet by passing the createStatement()
  • method one of three constant.
  • TYPE_FORWARD_ONLY
  • TYPE_SCROLL_INSENSITIVE
  • TYPE_SCROLL_SENSITIVE.
  • TYPE_FOREWARD_ONLY is the default setting.
  • The TYPE_SCROLL_INSENSITIVEconstant makesthe Resultsetinsensitive to the changes
  • made by anothercomponent.

55.

  • String url =jdbc:odbc:CustomerInformation;
  • String userID=sjec;
  • String password = comp
  • Private Connection conn;
  • try
  • {
  • Class.forName(sun.jdbc.odbc.JdbcOdbcDrive);
  • conn = DriverManager.getConnection(url,userID,password);
  • }
  • catch(ClassNotFoundException error)
  • {
  • System.out.println(Unable to load JDBC/ODBC bridge+error.getMessage());
  • }
  • catch(SQLException error)
  • {
  • System.out.println(can not connect to the datanase+error.getMessage());
  • }

56.

  • try { String query = SELECT FirstName,LastName FROM Customers;
  • stmt = con.createStatement(TYPE_SCROLL_INSENSITIVE );
  • rs = stmt.executeUpdate(query);
  • con.close();
  • }
  • catch(SQLException error) {
  • System.out.priintln( cannot connect to the database);}
  • try
  • {while(rs.next())
  • {
  • rs.last();
  • rs.first();
  • FirstName = rs.getString(1);
  • LastName= rs.getString(2);
  • System.out.println(FirstName++LastName);
  • }
  • }
  • catch(SQLException error)
  • {System.out.println(data entry error);
  • }

57. Updatable ResultSet

  • Rows contained in the ResultSet can be updatable by passing the createStatemenet() method of the
  • method of the Connection object the CONQUER_UPDATABLE.
  • Alternatively , the CONQUER_READ_ONLY constant can be passed to the createStatement method
  • to prevent the ResultSet from being updated.
  • There are 3 ways in which a ResultSet can be channged.
  • 1updating values in a row
  • 2 deleting a row
  • 3inserting a new row.

58. Update ResultSet

  • Once a executeQuery method of the Statement object returns a ResultSet, theupdatexxx()method is used to change the value of a column in the current row of the resultset.
  • Theupdatexxxmethod required2 parameters.
  • Theupdate Row()method is called after all theupdatexxx()methods are called.
  • The changes only occur in the ResultSet. The corresponding row in the table remains unchanged.

59. Update ResultSet

  • String url = "jdbc:odbc:CustomerInformation";
  • String userID = "jim";
  • String password = "keogh";
  • Statement st;
  • ResultSet rs;
  • Connection con;
  • try
  • {
  • Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver");
  • con = DriverManager.getConnection(url,userID,password);
  • }
  • catch (ClassNotFoundException error)
  • {
  • System.err.println("Unable to load the JDBC/ODBC bridge." + error);
  • System.exit(1);
  • }
  • catch (SQLException error)
  • {
  • System.err.println("Cannot connect to the database." + error);
  • System.exit(2);
  • }

60.

  • try {
  • String query = "SELECT FirstName,LastName FROM Customers WHERE FirstName = 'Mary' and LastName = 'Smith'";
  • st = con.createStatement(ResultSet.CONCUR_UPDATABLE);
  • rs = st.executeQuery (query);
  • }
  • catch ( SQLException error )
  • {
  • System.err.println("SQL error." + error);
  • System.exit(3);
  • }
  • boolean Records = Results.next();
  • try {
  • Results.updateString ("LastName", "Smith");
  • Results.updateRow();
  • st.close();
  • }
  • catch (SQLException error ) {
  • System.err.println("Data display error." + error);
  • System.exit(5);
  • }

61. Delete Row in the ResultSet.

  • rs.deleteRow(10)
  • Or
  • rs.absolute(10);
  • rs.deleteRow()

62. Insert Row in the ResultSet

  • Similar to update the Resultset.
  • TheinsertRowmethod is called after theupdatexxx()method.

63.

  • String url = "jdbc:odbc:CustomerInformation";
  • String userID = "jim";
  • String password = "keogh";
  • Statement st
  • ResultSet rs;
  • Connection con;
  • try {
  • Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver");
  • con = DriverManager.getConnection(url,userID,password);
  • }
  • catch (ClassNotFoundException error) {
  • System.out.println("Unable to load the JDBC/ODBC bridge." + error);
  • System.exit(1);
  • }
  • catch (SQLException error) {
  • System.out.println("Cannot connect to the database." + error);
  • System.exit(2);
  • }

64.

  • try {
  • String query = "SELECT FirstName,LastName FROM Customers";
  • st = con.createStatement(CONCUR_UPDATABLE);
  • rs = DataRequest.executeQuery (query);
  • }
  • catch ( SQLException error )
  • {
  • System.out.println("SQL error." + error);
  • System.exit(3);
  • }
  • boolean Records = rs.next();
  • try {
  • rs.updateString (1, "Tom");
  • rs.updateString (2, "Smith");
  • rs.insertRow();
  • rs.close();
  • }
  • catch (SQLException error ) {
  • System.out.println("Data display error." + error);
  • System.exit(5);
  • }

65. Transaction Processing

  • A database transaction consist of a set of SQL statements, each of which must be successfullycompleted for the
  • transaction to be completed.
  • If one fails, SQL statements that executedsuccessfully up to that point in the transaction must berolled back.
  • A database transaction is not completed until the commit() method of the Connection object iscalled. All SQL
  • statements executed prior to the call to the commit() method can berolled back.However once the commit()
  • method is called, none of the SQL statements can be rolledback.
  • Thecommit() method must be called regardless if the SQL statements is part of a transaction ornot.
  • commitmethodis automatically called , because DBMS has anAutoCommit features that is by default set to
  • true.

66.

  • While is processing a transaction, the AutoCommit features must be deactivated by calling
  • setAutoCommit(false);
  • Once the transaction is completed, thesetAutoCommit(true) iscalled again to reactivate the
  • AutoCommitfeature.

67.

  • String url = "jdbc:odbc:CustomerInformation";
  • String userID = "jim";
  • String password = "keogh";
  • Statementst1,st2 ;
  • Connection con;
  • try {
  • Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver");
  • con = DriverManager.getConnection(url,userID,password);
  • }
  • catch (ClassNotFoundException error) {
  • System.out.println("Unable to load the JDBC/ODBC bridge." + error);
  • System.exit(1);
  • }
  • catch (SQLException error) {
  • System.out.println("Cannot connect to the database." + error);
  • System.exit(2);
  • }

68.

  • try {
  • con.setAutoCommit(false)
  • String query1 = "UPDATE Customers SET Street = '5 Main Street' " +
  • "WHERE FirstName = 'Bob'";
  • String query2 = "UPDATE Customers SET Street = '10 Main Street' " +
  • "WHERE FirstName = 'Tim'";
  • st1= con.createStatement();
  • st2= con.createStatement();
  • st1.executeUpdate (query1 );
  • st2.executeUpdate (query2 );
  • con.commit();
  • st1.close();
  • st2.close();
  • con.close();
  • }

69.

  • catch(SQLException ex) {
  • System.out.println("SQLException: " + ex.getMessage());
  • if (con != null) {
  • try {
  • System.out.println("Transaction is being rolled back ");
  • con.rollback();
  • }
  • catch(SQLException excep) {
  • System.out.print("SQLException: ");
  • System.out.println(excep.getMessage());
  • }
  • }
  • }

70.

  • A transactiobn may consist of many tasks, some of which dont need to be rolled back should the entire transaction fail.
  • Ex:Consider order processing.These include
  • updating the customer account table
  • inserting the order into the pending order table
  • sending a customer a confirmation email.
  • Technically, all 3 tasks must be completed before the transaction is considered completed.suppose the email server is down when the transaction isready to send the customer a confirmation email. Should the entire transaction be rolled back ? Probably not since it is more importantthat the order continue to be processed(ie delivered). The confirmation notice can be sent once the email server is back online.

71.

  • Savepoint :
  • We cancontrol the number of tasks that are rolled back by using savepoint.
  • Asavepointis a virtual marker that defines the task at which the rollback stops
  • There can bemany savepoints usedin a transaction.
  • Each savepoint is identified by a unique name.
  • Savepoint s1 = con.setSavepoint ("sp1");
  • The savepoint name is then passed to the rollback() mathods to specify the point within the transaction
  • where the rollback is to stop.
  • The releaseSavepoint() method is called to remove the savepoint from the transaction.
  • The name ofthe savepoint that is to be removed is passed to the releaseSavepoint() method.

72.

  • String url = "jdbc:odbc:CustomerInformation";
  • String userID = "jim";
  • String password = "keogh";
  • Statementst1, st2 ;
  • Connection con;
  • try {
  • Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver");
  • con = DriverManager.getConnection(url,userID,password);
  • }
  • catch (ClassNotFoundException error) {
  • System.out.println("Unable to load the JDBC/ODBC bridge." + error);
  • System.exit(1);
  • }
  • catch (SQLException error) {
  • System.out.println("Cannot connect to the database." + error);
  • System.exit(2);
  • }

73.

  • try {con .setAutoCommit(false)
  • String query1 = "UPDATE Customers SET Street = '5 Main Street' " +
  • "WHERE FirstName = 'Bob'";
  • String query2 = "UPDATE Customers SET Street = '10 Main Street' " +
  • "WHERE FirstName = 'Tim'";
  • st1= con.createStatement();
  • st1.executeUpdate (query1);
  • Savepoint s1 = con.setSavepoint ("sp1");
  • st2= con.createStatement();
  • st2.executeUpdate (query2);
  • con.commit();
  • st1.close();
  • st2.close();
  • con.releaseSavepoint ("sp1");
  • con.close();
  • }catch ( SQLException error ){try {
  • con.rollback(sp1);}
  • catch ( SQLException error ){
  • System.out.println("rollback error." + error.getMessage());
  • System.exit(3);
  • }
  • System.out.println("SQL error." + error. getMessage()););
  • System.exit(4);
  • }

74.

  • addBatch method :
  • Another way to combine SQL statement into a transaction is to batch together these statements into a single transaction and then execute the entire transaction.
  • We can do this by using theaddBatch()method of the Statement object.
  • The addBatch() method receives a SQL statement as a parameter and places the SQL statement in the batch.
  • Onceall the SQL statements that comprise the transaction are included in the batch, theexecuteBatch()method is called to execute the enire batch at the same time.
  • The executeBatch method() returns an int array that contains the number of SQLstatements that were executed successfully.
  • The batch can be cleared of SQL statements by using theclearBatch()method.
  • The transaction must be committed using the commit() method.

75.

  • String url = "jdbc:odbc:CustomerInformation";
  • String userID = "jim";
  • String password = "keogh";
  • Statementst;
  • Connection con;
  • try {
  • Class.forName( "sun.jdbc.odbc.JdbcOdbcDriver");
  • con = DriverManager.getConnection(url,userID,password);
  • }
  • catch (ClassNotFoundException error) {
  • System.out.println("Unable to load the JDBC/ODBC bridge." + error);
  • System.exit(1);
  • }
  • catch (SQLException error) {
  • System.out.println("Cannot connect to the database." + error);
  • System.exit(2);
  • }

76.

  • try {
  • con .setAutoCommit(false)
  • String query1 = "UPDATE Customers SET Street = '5 Main Street' " +
  • "WHERE FirstName = 'Bob'";
  • String query2 = "UPDATE Customers SET Street = '10 Main Street' " +
  • "WHERE FirstName = 'Tim'";
  • st= con.createStatement();
  • st.addBatch(query1);
  • st.addBatch(query2);
  • int [ ] updated = st.executeBatch ();
  • con.commit();
  • st1.close();
  • st2.close();
  • con.close();
  • }
  • catch(BatchUpdateException error) {
  • System.out.println("Batch error.");
  • System.out.println("SQL State: " + error.getSQLState());
  • System.out.println("Message: " + error.getMessage());
  • System.out.println("Vendor: " + error.getErrorCode());

77.

  • int [ ] updated= error.getUpdatecount();
  • int count = updated.length();
  • for int - i = 0; i < count; i++) {
  • System.out.print (updated[i]);
  • }
  • SQLException sql = error;
  • While (sql != null)
  • {
  • System.out.println("SQL error " + sql);
  • sql = sql.getnextException();
  • }
  • try{
  • st.clearBatch();
  • }
  • catch(BatchUpdateException error) {
  • System.out.println("Unable to clear the batch: " + error.getMessage());
  • }
  • }

78. ResultSet Holdability

  • Whenever the commit() method is called, all ResultSet objects that were created for the transaction are closed.
  • We can control whether or not ResultSet objects are closedby passingfollowing parameter to thecreateStatement()
  • HOLD_CURSORS_OVER_COMMIT
  • CLOSE_CURSORS_AT_COMMIT

79. RowSets

  • The JDBCRowSetsobject is used to encapsulate a ResultSet for use with EJB.
  • A RowSetobject contains rows of data from the table that can be used in a disconnected operation.

80. Auto-Generated Keys

  • DBMS automaticallygenerate unique keys for a table as rows are insertedinto the table.
  • ThegetGeneratedKeys()method of the Statement object is called to return keys genetated by the DBMS.

81. MetaData

  • Metadata is data about data.
  • TheDatabaseMetaDatainterfaceis used toretrieve information about databases, table, column, and indexes among other information about the DBMS.
  • Metadata about the database is retrieved by callinggetMetaData()of Connection object.
  • The getMetaData() method returns aDatabaseMetaDataobject that contains information about the database and its component.
  • DatabaseMetaData object contains following methods.
  • getDatabaseProductName()
  • getUserName()
  • getURL()
  • getSchemas()
  • getPrimaryKeys()
  • getProcedures()
  • getTables()

82. ResultSet Metadata

  • There are2 types of metadata that can be retrieved from the DBMS.
  • metadata that describes the database
  • metadata that describes ResultSet
  • Metadata that describes the ResultSet is retrieved by calling the getMetaData() method ofthe ResultSet object.
  • This returns a Returns a ResultSetMetaData object.
  • ResultSetMetaDatarm = rs.getMetaData();
  • ResultSetMetaData objects provides following methods.
  • getColumnCount()
  • getColumnName(int number);
  • getColumnType(int number);

83. Exceptions

  • There are 3 kinds of exceptions that are thrown by JDBC methods. These are
  • SQLException
  • SQLWarnings
  • DataTruncation.
  • SQLExceptions commonly reflecta SQL syntax error in a query. This exception is mostly
  • caused by connectivity issues with the database.
  • The SQLWarning throws warnings received by the Connection from the DBMS.
  • Whenever data islost due to truncation of the data value, a DataTruncation exception is
  • thrown.

84.

  • execute() - will do the querying the database & also the update,insert,delete on the database.
  • executeUpdate() - only the update,insert,delete on the database.
  • executeQuery() - only the querying the database.
  • --------------------------------------
  • execute()- is for invoking the functions or stored procedures of SQL by the CallableStatement.
  • executeUpdata()- is for the operations such as insert, update or delete on SQL by PreparedStatement, Statement.
  • executeQuery() - is for operation select of Sql by PreparedStatement or Statement.
  • ----------------------------------------
  • executeUpdate() is for non selecting statements
  • executeQuery() is for selecting statements.
  • --------------------------------------------------------------------

85.

  • boolean execute() Executes the SQL statement in this PreparedStatement object, which may be any kind of SQL statement.
  • ResultSet executeQuery() Executes the SQL query in this PreparedStatement object and returns the ResultSet object generated by the query.
  • int executeUpdate() Executes the SQL statement in this PreparedStatement object, which must be an SQL INSERT, UPDATE or DELETE statement; or an SQL statement that returns nothing, such as a DDL statement.

86.

  • import java.util.*; String URL = "jdbc:oracle:thin:@amrood:1521:EMP"; Properties info = new Properties( ); info.put( "user", "username" ); info.put( "password", "password" ); Connection conn = DriverManager.getConnection(URL, info);