Your SlideShare is downloading. ×
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Unit 5-jdbc2
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Unit 5-jdbc2

813

Published on

java

java

Published in: Education, Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
813
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
80
Comments
0
Likes
0
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

Transcript

  • 1. JDBC
  • 2.
    • JDBC is Java API twhich allows 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/Native Code Driver.
    • Type 3 JDBC Driver.
    • Type 4 JDBC Driver.
  • 4.
    • Type 1 JDBC-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 the sun.jdbc.odbc.JdbcOdbcDriver class 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 the database 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 a serious 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 the native 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-side libraries 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 a middle-tier between the calling program and the database.
    • The middle-tier (application server) converts JDBC calls directly or 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 protocol which 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 the vendor 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 JDBC calls 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 source for 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:thin URL 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 they need 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 using method
    • DriverManager.getConnection()
    • The DriverManager.getConnection() method is passed the URL of the database, and the userID and password if
    • required by the DBMS.
    • The URL is a String object that contains the driver name and the name of the database that is being accessed.
    • The DriverManager.getConnection() method returns a Connection interface that is used throughout 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”);
    • Connection conn = DriverManager.getConnection(url,userID,password);
    • }
  • 21. Creating and executing a statement.
    • The con.createStatement() method is used to create a statement object.
    • The statement object is then used to execute a query and return a resultset object that contains the response from the
    • DBMS.
    • Statement stmt;
    • ResultSet rs;
    • Try
    • {
    • String query = “SELECT * FROM customers”;
    • stmt = con.createStatement();
    • rs = stmt.executeQuery(query);
    • con.close();
    • }
  • 22. Processing data returned by the DBMS
    • The java.sql.ResultSet object 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) Java Client Server Component
  • 25. Database Connection
    • Before the 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 the JDBC 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 the database.
    • A Connection object 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.
    • <subprotocol> which is the JDBc driver name.
    • <subname> which is the name of the database.
    • ex:String url = “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 the getConnection() method if access is granted.
    • otherwise getConnection() method throws a SQLException.
    • Sometimes the DBMS grants access to a database to anyone.
    • In this case getConnection(String url) method is used.
  • 29.
    • String url = “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 and require 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 be associated with a
    • Properties object, which is passed to the DBMS as a getConnection() parameter.
  • 33.
    • Connection con ;
    • Properties props = new Properties();
    • try
    • {
    • FileInputStream fis = 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(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());
    • }
  • 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, then create and 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.
    • PrepapedStatement which 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 used to execute queries that contain UPDATE and DELETE 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 =‘T’ where 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 the stored procedure and whose value is assigned using the setxxx() method.
    • The OUT parameter contain the value returned by the stored procedure. The OUT parameter must be registered using the registerOutParameter() and is retrieved by getxxx() 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.
    • The registerOutParameter 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
    • The ResultSet object contains methods that are used to copy data from the Result into a Java
    • variable for further processing.
    • Data in a ResultSet object is logically organized into a virtual table consisting of rows and column.
    • Resultset object also contains metadata such as column names, column size, and column data
    • types.
    • The ResultSet uses a virtual curser to point to a row of the virtual table.
    • We must move the virtual curser to each row and use other methods of the ResultSet object to
    • interact with the data stored in columns of that row.
    • The virtual curser is positioned above the first row of the data when the ResultSet is returned by
    • the executeQuery() method. This means that virtual curser must be moved to the first row using
    • next() method.
  • 50.
    • The next() method returns a boolean true if the row contains a data. Otherwise, a boolean false is returned indicating that no more rows exist in 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() parameter requires one parameter, which is an integer that 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 at the row specified by the integer
    • passed as a parameter to the absolute() method.
    • The relative() method moves the virtual curser the specified number 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 Statement object that is created using the createStatement() of the Connection
    • 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_INSENSITIVE constant makes the Resultset insensitive to the changes
    • made by another component.
  • 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.
    • 1 updating values in a row
    • 2 deleting a row
    • 3 inserting a new row.
  • 58. Update ResultSet
    • Once a executeQuery method of the Statement object returns a ResultSet, the updatexxx() method is used to change the value of a column in the current row of the resultset.
    • The updatexxx method required 2 parameters.
    • The update Row() method is called after all the updatexxx() methods are called.
    • The changes only occur in the ResultSet. The corresponding row in the table remains unchanged.
  • 59. Update ResultSet
    • String url = &quot;jdbc:odbc:CustomerInformation&quot;;
    • String userID = &quot;jim&quot;;
    • String password = &quot;keogh&quot;;
    • Statement st;
    • ResultSet rs;
    • Connection con;
    • try
    • {
    • Class.forName( &quot;sun.jdbc.odbc.JdbcOdbcDriver&quot;);
    • con = DriverManager.getConnection(url,userID,password);
    • }
    • catch (ClassNotFoundException error)
    • {
    • System.err.println(&quot;Unable to load the JDBC/ODBC bridge.&quot; + error);
    • System.exit(1);
    • }
    • catch (SQLException error)
    • {
    • System.err.println(&quot;Cannot connect to the database.&quot; + error);
    • System.exit(2);
    • }
  • 60.
    • try {
    • String query = &quot;SELECT FirstName,LastName FROM Customers WHERE FirstName = 'Mary' and LastName = 'Smith'&quot;;
    • st = con.createStatement(ResultSet.CONCUR_UPDATABLE);
    • rs = st.executeQuery (query);
    • }
    • catch ( SQLException error )
    • {
    • System.err.println(&quot;SQL error.&quot; + error);
    • System.exit(3);
    • }
    • boolean Records = Results.next();
    • try {
    • Results.updateString (&quot;LastName&quot;, &quot;Smith&quot;);
    • Results.updateRow();
    • st.close();
    • }
    • catch (SQLException error ) {
    • System.err.println(&quot;Data display error.&quot; + 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.
    • The insertRow method is called after the updatexxx() method.
  • 63.
    • String url = &quot;jdbc:odbc:CustomerInformation&quot;;
    • String userID = &quot;jim&quot;;
    • String password = &quot;keogh&quot;;
    • Statement st
    • ResultSet rs;
    • Connection con;
    • try {
    • Class.forName( &quot;sun.jdbc.odbc.JdbcOdbcDriver&quot;);
    • con = DriverManager.getConnection(url,userID,password);
    • }
    • catch (ClassNotFoundException error) {
    • System.out.println(&quot;Unable to load the JDBC/ODBC bridge.&quot; + error);
    • System.exit(1);
    • }
    • catch (SQLException error) {
    • System.out.println(&quot;Cannot connect to the database.&quot; + error);
    • System.exit(2);
    • }
  • 64.
    • try {
    • String query = &quot;SELECT FirstName,LastName FROM Customers&quot;;
    • st = con.createStatement(CONCUR_UPDATABLE);
    • rs = DataRequest.executeQuery (query);
    • }
    • catch ( SQLException error )
    • {
    • System.out.println(&quot;SQL error.&quot; + error);
    • System.exit(3);
    • }
    • boolean Records = rs.next();
    • try {
    • rs.updateString (1, &quot;Tom&quot;);
    • rs.updateString (2, &quot;Smith&quot;);
    • rs.insertRow();
    • rs.close();
    • }
    • catch (SQLException error ) {
    • System.out.println(&quot;Data display error.&quot; + error);
    • System.exit(5);
    • }
  • 65. Transaction Processing
    • A database transaction consist of a set of SQL statements, each of which must be successfully completed for the
    • transaction to be completed.
    • If one fails, SQL statements that executed successfully up to that point in the transaction must be rolled back.
    • A database transaction is not completed until the commit() method of the Connection object is called. All SQL
    • statements executed prior to the call to the commit() method can be rolled back. However once the commit()
    • method is called, none of the SQL statements can be rolled back.
    • The commit() method must be called regardless if the SQL statements is part of a transaction or not.
    • commit method is automatically called , because DBMS has an AutoCommit 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, the setAutoCommit(true) is called again to reactivate the
    • AutoCommit feature.
  • 67.
    • String url = &quot;jdbc:odbc:CustomerInformation&quot;;
    • String userID = &quot;jim&quot;;
    • String password = &quot;keogh&quot;;
    • Statement st1,st2 ;
    • Connection con;
    • try {
    • Class.forName( &quot;sun.jdbc.odbc.JdbcOdbcDriver&quot;);
    • con = DriverManager.getConnection(url,userID,password);
    • }
    • catch (ClassNotFoundException error) {
    • System.out.println(&quot;Unable to load the JDBC/ODBC bridge.&quot; + error);
    • System.exit(1);
    • }
    • catch (SQLException error) {
    • System.out.println(&quot;Cannot connect to the database.&quot; + error);
    • System.exit(2);
    • }
  • 68.
    • try {
    • con.setAutoCommit(false)
    • String query1 = &quot;UPDATE Customers SET Street = '5 Main Street' &quot; +
    • &quot;WHERE FirstName = 'Bob'&quot;;
    • String query2 = &quot;UPDATE Customers SET Street = '10 Main Street' &quot; +
    • &quot;WHERE FirstName = 'Tim'&quot;;
    • 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(&quot;SQLException: &quot; + ex.getMessage());
    • if (con != null) {
    • try {
    • System.out.println(&quot;Transaction is being rolled back &quot;);
    • con.rollback();
    • }
    • catch(SQLException excep) {
    • System.out.print(&quot;SQLException: &quot;);
    • System.out.println(excep.getMessage());
    • }
    • }
    • }
  • 70.
    • A transactiobn may consist of many tasks, some of which don’t 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 is ready to send the customer a confirmation email. Should the entire transaction be rolled back ? Probably not since it is more important that the order continue to be processed(ie delivered). The confirmation notice can be sent once the email server is back online.
  • 71.
    • Savepoint :
    • We can control the number of tasks that are rolled back by using savepoint.
    • A savepoint is a virtual marker that defines the task at which the rollback stops
    • There can be many savepoints used in a transaction.
    • Each savepoint is identified by a unique name.
    • Savepoint s1 = con.setSavepoint (&quot;sp1&quot;);
    • 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 of the savepoint that is to be removed is passed to the releaseSavepoint() method.
  • 72.
    • String url = &quot;jdbc:odbc:CustomerInformation&quot;;
    • String userID = &quot;jim&quot;;
    • String password = &quot;keogh&quot;;
    • Statement st1, st2 ;
    • Connection con;
    • try {
    • Class.forName( &quot;sun.jdbc.odbc.JdbcOdbcDriver&quot;);
    • con = DriverManager.getConnection(url,userID,password);
    • }
    • catch (ClassNotFoundException error) {
    • System.out.println(&quot;Unable to load the JDBC/ODBC bridge.&quot; + error);
    • System.exit(1);
    • }
    • catch (SQLException error) {
    • System.out.println(&quot;Cannot connect to the database.&quot; + error);
    • System.exit(2);
    • }
  • 73.
    • try { con .setAutoCommit(false)
    • String query1 = &quot;UPDATE Customers SET Street = '5 Main Street' &quot; +
    • &quot;WHERE FirstName = 'Bob'&quot;;
    • String query2 = &quot;UPDATE Customers SET Street = '10 Main Street' &quot; +
    • &quot;WHERE FirstName = 'Tim'&quot;;
    • st1= con.createStatement();
    • st1.executeUpdate (query1);
    • Savepoint s1 = con.setSavepoint (&quot;sp1&quot;);
    • st2= con.createStatement();
    • st2.executeUpdate (query2);
    • con.commit();
    • st1.close();
    • st2.close();
    • con.releaseSavepoint (&quot;sp1&quot;);
    • con.close();
    • } catch ( SQLException error ){ try {
    • con.rollback(sp1); }
    • catch ( SQLException error ){
    • System.out.println(&quot;rollback error.&quot; + error.getMessage());
    • System.exit(3);
    • }
    • System.out.println(&quot;SQL error.&quot; + 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 the addBatch() method of the Statement object.
    • The addBatch() method receives a SQL statement as a parameter and places the SQL statement in the batch.
    • Once all the SQL statements that comprise the transaction are included in the batch, the executeBatch() method is called to execute the enire batch at the same time.
    • The executeBatch method() returns an int array that contains the number of SQL statements that were executed successfully.
    • The batch can be cleared of SQL statements by using the clearBatch() method.
    • The transaction must be committed using the commit() method.
  • 75.
    • String url = &quot;jdbc:odbc:CustomerInformation&quot;;
    • String userID = &quot;jim&quot;;
    • String password = &quot;keogh&quot;;
    • Statement st;
    • Connection con;
    • try {
    • Class.forName( &quot;sun.jdbc.odbc.JdbcOdbcDriver&quot;);
    • con = DriverManager.getConnection(url,userID,password);
    • }
    • catch (ClassNotFoundException error) {
    • System.out.println(&quot;Unable to load the JDBC/ODBC bridge.&quot; + error);
    • System.exit(1);
    • }
    • catch (SQLException error) {
    • System.out.println(&quot;Cannot connect to the database.&quot; + error);
    • System.exit(2);
    • }
  • 76.
    • try {
    • con .setAutoCommit(false)
    • String query1 = &quot;UPDATE Customers SET Street = '5 Main Street' &quot; +
    • &quot;WHERE FirstName = 'Bob'&quot;;
    • String query2 = &quot;UPDATE Customers SET Street = '10 Main Street' &quot; +
    • &quot;WHERE FirstName = 'Tim'&quot;;
    • 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(&quot;Batch error.&quot;);
    • System.out.println(&quot;SQL State: &quot; + error.getSQLState());
    • System.out.println(&quot;Message: &quot; + error.getMessage());
    • System.out.println(&quot;Vendor: &quot; + 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(&quot;SQL error &quot; + sql);
    • sql = sql.getnextException();
    • }
    • try{
    • st.clearBatch();
    • }
    • catch(BatchUpdateException error) {
    • System.out.println(&quot;Unable to clear the batch: &quot; + 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 closed by passing following parameter to the createStatement()
    • HOLD_CURSORS_OVER_COMMIT
    • CLOSE_CURSORS_AT_COMMIT
  • 79. RowSets
    • The JDBC RowSets object is used to encapsulate a ResultSet for use with EJB.
    • A RowSet object contains rows of data from the table that can be used in a disconnected operation.
  • 80. Auto-Generated Keys
    • DBMS automatically generate unique keys for a table as rows are inserted into the table.
    • The getGeneratedKeys() method of the Statement object is called to return keys genetated by the DBMS.
  • 81. MetaData
    • Metadata is data about data.
    • The DatabaseMetaData interface is used to retrieve information about databases, table, column, and indexes among other information about the DBMS.
    • Metadata about the database is retrieved by calling getMetaData() of Connection object.
    • The getMetaData() method returns a DatabaseMetaData object 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 are 2 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 of the ResultSet object.
    • This returns a Returns a ResultSetMetaData object.
    • ResultSetMetaData rm = 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 reflect a 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 is lost 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 = &quot;jdbc:oracle:thin:@amrood:1521:EMP&quot;; Properties info = new Properties( ); info.put( &quot;user&quot;, &quot;username&quot; ); info.put( &quot;password&quot;, &quot;password&quot; ); Connection conn = DriverManager.getConnection(URL, info);

×