B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 JDBC (Java Database Connectivity): DEF: JDBC is one of the generic API developed by SUN Micro System and supplied as a part of a java software to deal with any type of database product to perform various database operations. Java Programmer JDBC API MS Access Oracle SQL My SQL SQL Server DB2 | | e.t.c., 1. Database Programming with java is known as JDBC similarly database programming in .NET is called DTO (Data Transfer Object) or DAO. The basic aim of JDBC is to achieve data persistency. 2. The process of storing the data permanently in the form of either in files or in database is known as data persistency. 3. In earlier software development, if any language programmer wants to achieve the data persistency then the language programmer must know the Vendor Specific API. For example if a C programmer want to store the data in Oracle database then C programmer must know the vendor specific library of Oracle database. 4. If the client organization decide to migrate one database to another database then the C programmer has completely rewrite the code by learning vendor specific library. 5. It is very difficult process to eliminate this limitation SUN Micros system has developed a generic API is called JDBC for the java programmers to deal with any number of databases without learning vendor specific API. 6. In order to deal with JDBC API we must import the packages called java.sql.*, javax.sql.*. In real world data persistency achieved in two ways they are 1 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 7. i) Through the concept of files ii) Through the concept of Database. 8. As a java programmer if we store the data in the form of the files then the data of the file can be manipulated by any un authorized user so that any files of any programming language never provides security in terms of username and passwords. Hence industry is not recommending data storing in files permanently 9. Therefore industry is highly recommended to store the data permanently store in the form of popular database products they provide enough security to prevent unauthorized modifications in the form of username and password. JDBC is a Partial Technology: 1. JDBS is one of the generic API which deals with many number of databases for performing various operations 2. JDBC is one of the specification/set of rules developed by the SUN Micro system because of the more famous of java software. 3. The rules of JDBC were implemented by database vendors like Oracle, IBM, Ingress Corporation e.t.c., in other words programmatically rules of JDBC given by SUN Micro system in the form of interfaces. 4. We know that interfaces contain Abstract methods. Database vendors have developed the columns of the classes by implementing the interfaces of JDBC. 5. In later days what classes implemented/developed by database vendors, those classes becomes product/database dependent classes. 6. Remembering product dependent classes by java programmer is difficult/complex. Here SUN Micro system has collected all the product dependent classes from database vendors and prepared common classes and kept in the form of packages. 7. In real world development all packages will be released in the form of jar files (java archive) along with the interfaces development of JDBC by SUN Micros system. 8. Some of the classes are also developed by Database vendors. Hence JDBC is one of the Partial Technology but not a language. 9. In pure Technology development interfaces are developed by language vendors corresponding classes are developed by either server vendors or database vendors completely. NOTE: Software is said to be language if and only if rules and their implementations developed by language vendors only. Languages are installable softwares whereas technologies are not installable because they are not containing complete implementation by one vendor. 2 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 Steps for developing a JDBC Application: 1. JDBC Drivers: Java Program JDBC Drivers Database Softwares 1. JDBC Driver is one of the predefined class developed by Database vendors for establishing the communication between java program and database software or JDBC Driver is one of middleware layer between java application and database software. 2. Establishing the communication between java program and database software is nothing but creating an Object of appropriate JDBC Driver for example if we write an Object of OracleDriver class in our java program then our java program can establish the communication with oracle database software 3. Similarly when we create an Object of DB2 Driver class then our java program establishes the communication between DB2 database software. 4. Here Oracle Driver (Oracle Corporation, DB2 Driver(IBM)) are the examples of JDBC Drivers JDBC drivers are developed by database vendors in the language called java and they are coming or supplied along with database softwares. A java programmer is not responsible for development of JDBC drivers but java programmer always use database Drivers for establishing the communication between java program and database software. 5. SUN Micro system has classified into all available JDBC drivers four categories those are i. Type1 drivers or (JDBC-ODBC bridge drivers) ii. Type2 drivers or native drivers iii. Type 3 drivers or net protocol drivers iv. Type 4 drivers or all java/pure/thin drivers ODBC Drivers (Open Database Connectivity): ODBC Drivers: 1. ODBC Drives specifications (rules) developed by Xopen Company. The ODBC Specification says develop all ODBC Drivers in a language called C. Which is one of the platform independent language. 3 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 2. All Database vendors come forward and developed drives in a language called C. ODBC drivers are meant for establishing the communication channel or bridge between non java applications and database softwares all the database vendors has given the ODBC Drivers to Xopen Company and Xopen company supplied these ODBC drivers along Microsoft Operating Systems. 3. The following diagram gives the view about the communication system between java/non java application and database software. DSN (Data Source Name): 1. A DSN is a Configured item or variable created in the local machine which always gives location of the database in simple words DSN is one of the alternative name create by the programmer for ODBC Drivers. 2. As a java programmer we use DSN in their applications for establishing the communication between java/non java applications and database software. 4 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 ODBC Driver for Oracle Non java – java application ODBC Drivers ODBC Driver for MySQL MySQL databse ODBC Driver for Paradax Database Paradax ODBC Driver for DB2 5 Oracle database DB2 database B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 ODBC Driver for MsAccess Ms Access Database Q) What are the differences between JDBC drivers and ODBC drivers? JDBC Drivers ODBC Drivers 1. JDBC Drivers specification 1. ODBC Drivers specification developed by SUN Micro system and developed by Xopen and JDBC JDBC drivers are implemented by drivers are implemented by Database Database vendors. vendors. 2. All database vendors implemented 2. All database vendors implemented JDBC Drivers in java language. ODBC Drivers in C language. 3. All the JDBC drivers are Platform 3. All the ODBC drivers are Platform independent. dependent. 4. All the JDBC drivers are supplied 4. All the ODBC Drivers are supplied through database softwares. for Microsoft Operating Systems. 5. JDBC drivers are purely meant for 5. ODBC Drivers are meant for both establishing the communication java and non java programmers for between java applications and establishing communication between universal softwares. database softwares. 6. ODBC drivers are not recommended 6. Industry is highly recommended to by the industry to communication use JDBC Drivers to communicate with the database because they with the database because they posses/gives platform dependency. gives/posses platform independency. Static Block: 1. In java library we come across various predefined classes which are present in various predefined packages. 2. While we are executing the java program, the corresponding classes will be loaded in the main memory and executes static blocks of that class only once first during the loading time, later executes main() only once. 6 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 3. Each and every time constructors will execute depends on the number of the Objects we create and execute user defined methods depends on the number of times the programmer is calling. 4. A class of java may or may not contain static blocks. EX: class first { first() { System.out.println("I am from Constructor"); } void first() { System.out.println("I am from method"); } static { System.out.println("I am from business logic static"); } } class stsdemo { static { System.out.println("I am from execution logic static"); 7 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 } public static void main(String args[]) { first f=new first(); f.first(); } } OUTPUT: C:\>java stsdemo I am from execution logic static I am from business logic static I am from Constructor I am from method Observation point: Here first execution logic static block first execute only once, next business logic static execute only once, next Constructor will execute each and every time, method also execute each and every time. Q) Can we write a java program without main ()? A) Yes, through static blocks we can execute the java program. EX: class first { void first() { System.out.println("hello"); 8 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 } } class stsdemo { static { System.out.println("Hello"); } } OUTPUT: C:\>java stsdemo Hello Exception in thread "main" java.lang.NoSuchMethodError: main P) Write a java program which illustrate the concept of static blocks. //stp.java package stp; public class stp { static { System.out.println("I am from static block"); } 9 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 public stp() { System.out.println("stp DC"); } public void disp() { System.out.println("STP-Disp"); } } //Stpdemo.java import stp.*; class stpdemo { public static void main(String args[]) { try { Class c=Class.forName(args[0]); String cname=c.getName(); System.out.println("Class name="+cname); } catch(ClassNotFoundException ce) 10 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 { System.err.println(args[0]+"class not exists"); } } } OUTPUT: C:\>java stpdemo stp.stp I am from static block Class name=stp.stp Architecture of Type-1 Driver: 1. Type11 Driver developed by SUN Micro system and it is known as JDBC – ODBC bridge driver. 2. Type-1 Driver implemented by SUN Micro system in C language. So that Type-1 driver always posses platform dependent. 3. Type-1 Driver always supplied as a part of Java software 4. Type-1 Driver of SUN Micro system makes use of DSN to communicate with the database software. As on today real world applications never uses Type-1 Driver but it is used only for testing purpose. 5. The following Diagram gives architecture of Type-1 Driver. 11 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 The following steps gives to and pro calls between Java program and Database Software. 1. We write java program making use of JDBC API. 2. Java programs makes use of JDBC Driver (Type-1) for establishing the communication between Java program and Database software. 3. Since Type-1 driver of JDBC is not having the capability to directly communicate with database software so that Type – 1 Driver makes use of ODBC driver this combination is known as JDBC-ODBC Bridge. The role of JDBC-ODBC Bridge is to convert java related calls into Database equivalent calls and Database equivalent calls to java equivalent calls during its communication. 4. It is not possible to use ODBC Driver in the Java program directly so that we use an alias name of ODBC driver called DSN which will give collection of Database software where the programmer is interested in communicating. 5. All Database related calls(queries) are reaching to the Database software through DSN. 6. Database queries are executed by the Database engines in the Database layer 7. 8,9) The result of database software given to the Java application through DSN and JDBC-ODBC bridge. 10. * JDBC bridge converts Database equivalent calls to Java equivalent calls. 11. The result of the Database reaches to the java program and it will be displayed on the Console. In the above steps 1,2,3,4,5 are called “to calls” from Java program and remaining steps are “pro calls” between Database software and Java application. 12 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 Type-1 Driver allows us to develop only two-tier applications (Java application, Database Software). Note: Type: JDBC-ODBC bridge Driver Vendor: SUN Micro System Driver name: sun.jdbc.odbc.JdbcOdbcDriver Jar file: rt.jar(jdk 1.5, jdk 1.6/lib) Software requirement: jdk1.5/jdk 1.6 Database software: Oracle 8i/9i/10g/11g. Implementation language: C In Type -1 Driver, application development JDBC-ODBC driver name is fixed and DSN names are verifying from one database software to Database software Steps for developing JDBC applications: In order to write any JDBC application, SUN Micro system has prescribed the following guidelines. 1) Load or register the JDBC drivers with the Driver Manager Service. 2) Obtain the communication by making use of Driver Manager Service. 3) Create the statement Object for sending the queries from java program to Database software. 4) Use statement Object to send the queries from java application to Database software. 5) Java program process the Database result. 6) Close the connection/relinquish (release JDBC Objects). i) Load or register the JDBC drivers with the Driver Manager Service: In java programming we have predefined service called Driver Manager Service and it is always used for registering or loading the JDBC Drivers. Unless and until loading the Drivers in the Driver Manager Service, we can’t get any communication with the Database software registering or loading the Drivers is nothing but creating an Object of appropriate Driver Class and place that Object in the Driver Manager Service in Java programming to get the Driver Manager Service we have a predefined class called Driver Manager which is present in a predefined package called java.sql.*, java.sql.DriverManager Class contains the following method for loading the Drivers only once. 13 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 Java.sql.DriverManager Public static void RegisterDriver (java.sql.Driver) Here java.sql.Driver is the super interface(developed by SUN) for all JDBC drivers (developed by other party Vendor) class JdbcOdbcDriver implements Driver { class OracleDriver implements Driver { -------------------} EX: JdbcOdbceDriver jd=new JdbcOdbcDriver(); DriverManager.registerDriver(jd); { System.out.println(“Type-1 Driver loaded”); } EX: OracleDriver od=new OracleDriver(); DriverManager.registerDriver(od); { System.out.println(“Type-4 Drivers loaded”); } The process of registering drivers with Driver Manager Service is known as explicit drivers registration. Implicit registration/Loading of the JDBC Drivers in the Driver Manager Service: Industry is highly recommended to use implicit registration of the drivers with Driver Manager Service. To perform implicit registration of the drivers we use Class.forName(-) 14 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 EX: Class.forName(sun.jdbc.odbc.JdbcOdbcDriver) When the above statement is executed the following implicit actions will be performed by the JVM. 1) JVM loads JdbcOdbc driver class in the main memory of the computer. 2) JVM automatically calls static blocks of JdbcOdbcDriver class only once. 3) As a part of JdbcOdbcDriver class, in the static block SUN Micro System developers has written the following steps a) Created an Object of JdbcOdbc Driver class b) An Object of JdbcOdbcDriver class placed in the Driver Manager Service. c) In general the above procedure is applicable for all JdbcDrivers. class JdbcOdbcDriver implements Driver. { static { ----------------JdbcOdbcDriver jd=new JdbcOdbcDriver(); DriverManager.registerDriver(jd); ---------------} Industry is always recommended to use implicit registration on loading of the drivers with help of Class.forName(-). (If we would like to know internal details of class we use Class= beore Class.forname) ii) Obtain the connection by making use of DriverManagerService: In order to obtain a connection from the specified Database the appropriate Jdbc drivers must be loaded in the DriverManager service first. That is without loading the Drivers obtaining connection from specific Database is not possible. In order to get the connection from the Database we must use the following methods present in DriverManager Service Java.sql.DriverManager a) Public static Connection getConnection(String url); b) Public static Connection getConnection(String url,String uname,String pwd); c) Public static Connection getConnection(String url,Properties p); 15 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 a) Public static Connection getConnection(String,url): This method is used for obtaining conncetion from unsecured Database like MS Access, MS Excel e.t.c. because these database doesn’t contain user name and password. b) Public static Connection getConnection(String url,String uname,String pwd): This method is used for obtaining the connection from Secured Database like Oracle,DB2,SQL Server e.t.c., EX: connection oracon=DriverManager.getConnection(“Jdbc:Odbc:sathya”,”scott”,”tiger”) connection acon=DriverManager.getConnection(“Jdbc:Odbc:Accdsn)//for Access DB Here oracon,accon are two indirect Object of java.sql.Connection interfacxe but they are direct Objects of subclasses of connetion interfaces. Conncetion interface developed by SUN Micro system and whose sub class developed by Database vendors. c) Public static Connection getConnection(String url,Properties p): This method is used for obtaining both from secured and unsecured Databases. These types of connections are known as flexible connections. Syntax for url format of Type-1 Driver: Main Protocol : subprotocol : DSN Here in JDBC applications main protocol always represents JDBC and whose role is converts java related calls into database calls. Sub protocol represents always ODBC and further it will be changing depends on the Database vendor and the purpose of the protocol is taking the Database calls and hand over to the Database through DSN. DSN represents an alias name of ODBC Driver which is configured to the local machine it always locates the connection of the Database Jdbc:Odbc:Accdsn Jdbc:Odbc:Oradsn Jdbc:Odbc:Xldsn Note: 16 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 1. Jdbc, Odbc are known as proprietary protocols which will establish the communication between two specific applications. 2. HTTP,FTP,SMTP,POP e.t.c., are known as Application level protocol which will establish the communication between universal applications. 3. TCP and UDP are known as Network level protocol s and it will establish the communication between one network and other network. P) Write a Jdbc application which illustrate the concept of loading the drivers and obtaining the connection from Oracle database by using Type-1 Driver. import java.sql.*; import sun.jdbc.odbc.JdbcOdbcDriver; class Firstjdbc { public static void main(String args[]) throws Exception { //step-1 JdbcOdbcDriver jd=new JdbcOdbcDriver(); DriverManager.registerDriver(jd);//explicit driver loading //Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //implicit loading System.out.println("type-1 Driver loading"); //step-2 Connection con=DriverManager.getConnection("jdbc:odbc:siva","scott","tiger"); if(con!=null) { System.out.println("connection obtained from oracle"); } else 17 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 { System.out.println("connection failed"); } } } /* OUTPUT C:\>java Firstjdbc type-1 Driver loading connection obtained from oracle */ iii) Create the statement Object for sending the queries from java program to Database software. In order to send a query to java application database software, we must create an Object od Statement interface. Statement is one of the predefined interface which is present in java.sql.* package and whose Object purpose is to carry the query from java application to Database software. In order to create an Object of statement interface we use the following method present in Connection interface java.sql.Connection public statement CreateStatement() EX: Statement st=con.CreateStatement(); Here st is an indirect Object of statement interface and it is one of the direct Obejct of sub class of Statement interface. Here st is ready to use to take query from java application to the Database software 18 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 4. Use Statement Object to sending the queries to the Database: In order to send queries from java application to the Database software we use the following methods present in Statement interface. Java.sql.Statement a) public int executeUpdate(String) b) public ResultSet execute(String) c) public boolean execute(String) a) public int executeUpdate(String): Here this method is used for executing non-select queries(insert,update,delete) the parameter String represents name of the non-selected query this method returns int values as a return type if intValue is Positive then query is executed successfully executed. If intValue is zero then query is not executed successfully. EX: String qry=”insert into dept values(60,’filename’,’hyd’) int res =st.executeUpdate(qry); System.out.println(res+”rows inserted”); int res1=st.executeUpdate(“delete from emp where deptno=10); System.out.println(res+”Rows deleted”); b) public ResultSet execute(String): This method is used for executing select queries the parameter String represents name of the query the return type of this method is ResultSet. ResultSet is one of the predefined interface which is used for holding the number of records after execution of select query in the Database software. EX: ResultSet rs=st.executeQuery(“select * from dept”); rs 1 Deptno 10 20 30 2 3 Dname Finance HR Marketing Loc Hyderabad Delhi Banglore c) public boolean execute(String): This method is used for executing both select and non select queries. The return type of this method is boolean if boolean value is true then the query is executed successfully. If it is false the query is not executed successfully. 19 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 EX: boolean res=st.execute(“select * from dept”); System.out.println(res) //true. 5. Java program process the Database result: Processing the Database result is nothing but obtaining the result from Database and use in our java program. EX: figure 1. In order to retrieve the data from ResultSet interface Object we have two approaches those are i) ii) Based on Column number or Column name in the form of String type Based on Column number or Column name in the form of Original type. In JDBC programming after retrieving the records from the database they are available in the form of Object of ResultSet interface and whose Database column names with the numbers 1,2,3,------,n. When we create an Object of ResultSet which is by default pointing just before the first record. To retrieve the further records we need to move ResultSet objects to further records after checking whether we have next record or not. Methods in ResultSet: 1. 2. 3. 4. 5. public boolean next() public String getString(int Columnno) public String getString(String Columnname) public xxx getXxx(int columnno) public xxx getXxx(String Columnname) Columnno Columnname Columnno Columnname String Original Type 1. public boolean next(): This method returns true provided ResultSet interface Object is having next record. Once it returns true, the ResultSet interface Object will be point that particular record. This method returns false provided ResultSet interface Object have does not have any next record. 2. public String getString(int Columnno) 3. public String getString(String Columnname): These two methods are used to retrieve the data from the Database in the form of the String based on column number or based on column name. EX: ResultSet rs=st.executeQuery(“Select * from dept”); rs 20 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 Deptno Dname Finance 10 20 HR 30 Marketing Obtaining the records based on column numbers. Loc Hyd Ban Chn While(rs.next) { String dno=rs.getString(1); String dname=rs.getString(2); String loc=rs.getString(3); System.out.println(dno+” “+dname+” “+loc); } Obtain the records based on the column names While(rs.next) { String dno=rs.getString(deptno); String dname=rs.getString(dname); String loc=rs.getString(loc); } 4. public xxx getXxx(int columnno) 5. public xxx getXxx(String Columnname): These methods are used for retrieving the data of the Database in the original form. Either based on Column number or based on Column name. while(rs.next) { int deptno=rs.getString(1); 21 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 String dname=rs.getString(2); String loc=rs.getString(3); } Obtaining records based on columns While(rs.next) { Int deptno=rs.getint(deptno); String dname=rs.getString(dname); String loc=rs.getString(loc); } Note: By default JDBC 2.X features, an Object of ResultSet interface allows us to retrieve the data only in forward direction. But not in backward direction. This type of ResultSet is not scrollable “ResultSet”. P) Write a JDBC program for inserting a record into dept table of Database. import java.sql.*; import sun.jdbc.odbc.JdbcOdbcDriver; class Jdbcnew1 { public static void main(String args[])throws Exception { //step-1 // JdbcOdbcDriver jd=new JdbcOdbcDriver(); //DriverManager.registerDriver(jd); //explicit Registration 22 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); System.out.println("Driver registered"); //Step-2 Connection con=DriverManager.getConnection("jdbc:odbc:siva","scott","tiger"); //Step-3 Statement st=con.createStatement(); //Step-4 String qry="insert into dept values(50,'Acc','hyd')"; int res=st.executeUpdate(qry); //step-5 System.out.println(res+"rows inserted"); //step st.close(); con.close(); } } P) Write a JDBC program to accept empno from cmd prompt and enter values. import java.sql.*; import sun.jdbc.odbc.JdbcOdbcDriver; import java.util.*; class practicedemo 23 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 { public static void main(String args[])throws Exception { //step-1 // JdbcOdbcDriver jd=new JdbcOdbcDriver(); //DriverManager.registerDriver(jd); //explicit Registration Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); System.out.println("Driver registered"); //Step-2 Connection con=DriverManager.getConnection("jdbc:odbc:siva","scott","tiger"); //Step-3 int eno=Integer.parseInt(args[0]); Scanner s=new Scanner(System.in); System.out.println("enter emp mumber"); String s1=s.nextLine(); //step-3 Statement st=con.createStatement(); //step-4 ResultSet rs=st.executeQuery("select ename,job,sal from emp where empno="+eno); //step-5 if(rs.next()) { 24 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 String ename=rs.getString(1); String job=rs.getString(2); String sal=rs.getString(3); System.out.println("emp name="+ename); System.out.println("emp job="+job); System.out.println("emp sal="+sal); } else { System.out.println("no record found"); } rs.close(); st.close(); con.close(); } } /* OUTPUT C:\>java practicedemo 7788 Driver registered enter emp mumber 7788 emp name=RAJU 25 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 emp job=CLERK emp sal=5000 */ Observations: 1. If a JDBC program violates the constraints of a table/Database then we get a predefined exception called java.sql.Exception. 2. Whatever the Database operations perform on the table(inserting,deleting,modifying) those operations are auto committed. That is explicitly the JDBC programmer need not use Committ command. 6. Close Connection/Relinquish(release) JDBC Objects: After completion of Database operations, it is responsibility of the JDBC programmer to close or release the JDBC related Objects those are Close the Objects of ResultSet, Statement and Connection interface. EX: rs.close(); Con.close(); St.close(); Here close is the method present in ResultSet, Statement and connection interfaces. P) Write a JDBC program which will remove a record by accepting deptno dynamically. import java.sql.*; class prt { public static void main(String args[])throws Exception { //step-1 Class.forName("oracle.jdbc.driver.OracleDriver"); 26 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 System.out.println("Driver Loaded"); //Step-2 Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger"); System.out.println("Connection established from Oracle"); //step-3 Statement st=con.createStatement(); int no=Integer.parseInt(args[0]); int p1=st.executeUpdate("delete from vst where no="+no); if(p1>0) System.out.println(p1+"Record deleted"); else System.out.println("no record found"); st.close(); con.close(); } } P) Write a JDBC Program which will select empno, name, salary, designation based on employee number accept the employee number from command prompt. import java.sql.*; import sun.jdbc.odbc.JdbcOdbcDriver; class Jdbcnew1 27 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 { public static void main(String args[])throws Exception { //step-1 // JdbcOdbcDriver jd=new JdbcOdbcDriver(); //DriverManager.registerDriver(jd); //explicit Registration Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); System.out.println("Driver registered"); //Step-2 Connection con=DriverManager.getConnection("jdbc:odbc:siva","scott","tiger"); //Step-3 Statement st=con.createStatement(); //Step-4 int no=Integer.parseInt(args[0]); ResultSet res=st.executeQuery( "Select * from emp where empno="+no); //step-5 if(res.next()) { System.out.println("Employee name"+res.getString(2)); System.out.println("Employee name"+res.getString(4)); 28 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 System.out.println("Employee name"+res.getString(6)); } //Step-6 st.close(); con.close(); } } Type -1 Driver Advantages: 1. By using Type-1 Driver one can communicate with any number of Databases. 2. Type-1 Driver is easy to implement and easy to remember for establishing the communication between java application and Database software. Disadvantages: 1. Type-1 Driver implemented by SUN Micro System in C language so that Type-1 Driver possesses platform dependency. This is not recommended. 2. In order to use Type-1 Driver, it is mandatory to JDBC programmer to create DSN in the local machine. So that local settings of the PC are not recommended because when the JDBC application us changing from one PC to another local PC programmer need to perform required local settings. 3. Type-1 Driver gives more number of to and pro calls in other words there exists more number of round trips between java application and Database software which makes the JDBC application to get less performance. 4. Type-1 Driver is used only for testing purpose but not for real implementation purpose for application development. 5. Type-1 Driver allows us to develop two tier applications only but not three tier applications. Type-4 Deriver (All Java, pure Java, Thin): 1. Type-4 Drivers developed by Database vendors. 2. Type-4 Drivers are supplied along with Database software for example Oracle corporation developed Type-4 Driver on the name of predefined class called OracleDriver and it is present in a predefined package called oracle.jdbc.driver.*; 29 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 3. IBM has developed Type-4 Driver name DB2 Driver and it is present in predefined package called ibm.jdbc.Driver.*. All the Database vendors has developed Type-4 driver in Java language so that all Type-4 drivers possesses platform independency. While we are using Type-4 Driver as a part of our JDBC application we doesn’t require any DSN. Architecture: Application Layer Database Layer Java Application Database Software 1 JDBC API 4 7 6 2 J D B C 5 5 5 3 In the above architecture the Type-4 Driver converts java calls to Database equivalent calls and Database equivalent calls to java related calls. Oracle Corporation has supplied OracleDriver class in the following jar files. Classes12.jar or jdbc14.jar. As a java Developer when we use OracleDriver, it is mandatory for the JDBC programmer to set classpath. All the above jar files are present in Oracle software in the following location. C:\oracle\product\10.2.0\db_1\jdbc\lib\classes12.jar;.; Note to show classpath after setting it just type echo %classpath% 30 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 Set classpath= C:\oracle\product\10.2.0\db_1\jdbc\lib\classes12.jar;.; Before compiling the JDBC program we need to set the above class path. Loading or Registering Type-4 Driver(OracleDriver): 1. Loading implicitly Class.forName( “oracle.jdbc.driver.OracleDriver”) 2. Loading explicitly OracleDriver od=new oracle.jdbc.driver.OracleDriver; (or) DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver); Obtaining the connection from the Database software by using Type-4 Driver: Syn: Main protocol: sub protocol: Logical name of Type-4: @ DNS or IP address: port number: Serive id a) Here Main Protocol is always JDBC b) Sub protocol is always represents Database vendor name (for example Oracle Database vendor the sub protocol is Oracle). c) Logical name of Type-4 of OracleDriver is always thin d) DNS(Domain Name Service): Represents physical name of the machine where the Database software resides the default DNS of every computer is localhost ( we can write out IP address). IP address means internet protocol address of physical machine where Database software resides. By default IP address of every machine is 127.0.0.1. e) Port Number: It is one of the Logical numerical ID” where the Database software is running. The default protnumber of Oracle 1521(fixed) can’t be change. f) Service ID: It is one of the alternative name or alias name for universal software called Oracle, when it is installed in our pc. To find the Service ID of Oracle Database use the following SQL> select * from globalname Alternatively we can find the service id and port number from one of the file called tnsnames.ora which is found in D:/oracle/ora92/network/admin folder Another alternative way is go to search and type tnsname.ora EX: jdbc:oracle:thin:@localhost:1521:sathya Q) What will you give in the place of localhost in Type-4 driver? A) The destination machine host name. For example it is web application then remove host name and port number and give proper url. 31 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 Note: Summary of OracleDriver(Type-4) Driver Name : OracleDriver Fully Qualified Name: oracle.jdbc.driver.OracleDriver Jar files : Class111.jar, Classes12.jar Vendor Name : Oracle Corporation Implementation Language : Java Logical Name : thin P) Write a java program which will load Type-4 Drivers and Obtain Type-4 Driver by using OracleDriver and obtain the connection from Oracle. import java.sql.*; import oracle.jdbc.driver.OracleDriver; class practicedemo { public static void main(String args[])throws Exception { //OracleDriver od=new OracleDriver(); // DriverManager.registerDriver(od); Class.forName("oracle.jdbc.driver.OracleDriver"); System.out.println("drivers loaded"); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger"); 32 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 System.out.println("Connection Obtained from oracle"); } } Note: We can insert like this but it is not recommended approach P) Write a JDBC program to insert a record into Database table. import java.sql.*; class jdbcprog2 { public static void main(String args[]) throws Exception { Class.forName("oracle.jdbc.driver.OracleDriver"); System.out.println("Drivers loaded"); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger"); System.out.println("Connection Obtained"); Statement st=con.createStatement(); String qry="insert into sps values(50,'Acc',5000)"; int res= st.executeUpdate(qry); st.close(); con.close(); if(res>0) { System.out.println(res+"one row inserted"); } 33 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 else { System.out.println(res+"not inserted"); } } } P) Write a JDBC Program to give input from keyboard and get result. import java.sql.*; import java.util.*; //import oracle.jdbc.driver.OracleDriver; class prt { public static void main(String args[])throws Exception { // OracleDriver od=new OracleDriver(); //DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver()); Class.forName("oracle.jdbc.driver.OracleDriver"); System.out.println("drivers loaded"); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger"); System.out.println("Connection Obtained from oracle"); int eno=Integer.parseInt(args[0]); Scanner s=new Scanner(System.in); 34 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 System.out.println("enter emp mumber"); String s1=s.nextLine(); //step-3 Statement st=con.createStatement(); //step-4 ResultSet rs=st.executeQuery("select ename,job,sal from emp where empno="+eno); //step-5 if(rs.next()) { String ename=rs.getString(1); String job=rs.getString(2); String sal=rs.getString(3); System.out.println("emp name="+ename); System.out.println("emp job="+job); System.out.println("emp sal="+sal); } else { System.out.println("no record found"); } rs.close(); st.close(); 35 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 con.close(); } } To perform Delete operation import java.sql.*; import java.util.*; class practicedemo { public static void main(String args[])throws Exception { //step-1 Class.forName("oracle.jdbc.driver.OracleDriver"); System.out.println("Driver Loaded"); //Step-2 Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger"); System.out.println("Connection established from Oracle"); //step-3 Statement st=con.createStatement(); int no=Integer.parseInt(args[0]); Scanner s=new Scanner(System.in); String s1=s.nextLine(); int p1=st.executeUpdate("delete from vst where no="+no); System.out.println("enter a number to delete record"); 36 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 System.out.println("One record deleted sucessfully"); st.close(); con.close(); } } Q) What are Class.forName(-) the differences betweenDriverManager.registrationDriver DriverManager.registerDriver 1. This statement is used for registering or loading the Drivers explicitly. 2. This Statement verifies the JdbcDriver availability at compile time and registered at runtime time. 3. This approach is not recommended by industry because explicit driver registration done by Java programmer. and Class.forName(-) 1. This statement is used for registering or loading the Drivers implicitly with the help of inbuilt static blocks. 2. This Statement verifies the JdbcDriver availability and registration at runtime. 3. This approach is recommended by industry because implicit driver registration done by Drivers Developers(Database developers) Dealing with MS Access: we know that MS Access is one of the partial RDBMS product because all the rules of RDBMS (Codd Rules) are not completely satisfy. Microsoft has not develop any Type-4 Driver to dealing with MS Access Database. MS Access doesnot contain user name and passwords. In general any universal Database is containing user names and passwords such Database vendors develops Type-4 driver for directly interacting such Database. EX: Oracle, DB2, Sybase e.t.c., In general if any Database product does not contain any user name and password, there is no Type-4 Driver developed by Database vendors. As a Java programmer to retrieve the data or to perform various Database operations we use Type-1 Driver with the help of DSN Creation. EX: MS Access, MS Excel e.t.c., Steps for dealing with MS Access: 1. Create a Database in MS Access. 2. Create DSN. 37 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 3. Write a JDBC code to communicate with MS Access. P) Write a JDBC program to retrieve the data from MS Access. import java.sql.*; import sun.jdbc.odbc.JdbcOdbcDriver; import java.util.*; class practicedemo1 { public static void main(String args[])throws Exception { //step-1 // JdbcOdbcDriver jd=new JdbcOdbcDriver(); //DriverManager.registerDriver(jd); //explicit Registration Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); System.out.println("Driver registered"); //Step-2 Connection con=DriverManager.getConnection("jdbc:odbc:asps"); //Step-3 int eno=Integer.parseInt(args[0]); Scanner s=new Scanner(System.in); System.out.println("enter emp mumber"); String s1=s.nextLine(); 38 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 //step-3 Statement st=con.createStatement(); //step-4 ResultSet rs=st.executeQuery("select ename,job,sal from emp where empno="+eno); //step-5 if(rs.next()) { String ename=rs.getString(1); String job=rs.getString(2); String sal=rs.getString(3); System.out.println("emp name="+ename); System.out.println("emp job="+job); System.out.println("emp sal="+sal); } else { System.out.println("no record found"); } rs.close(); st.close(); con.close(); } } 39 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 /* OUTPUT C:\>java practicedemo 7788 Driver registered enter emp mumber 7788 emp name=RAJU emp job=CLERK emp sal=5000 */ Dealing with MS Excel: we know that MS Excel is meant for financial calculations in the areas like banking, insurance, audit e.t.c. In the most of the real world applications development MS Excel will be used a minor Database and Oracle as a major Database Like MS Access, MS Excel also does not have user name and password. So that vendor Microsoft has not developed any Type-4 Driver. As a Java programmer to interact with the MS Excel we need to use Type-1 Driver by creating a DSN for MS Excel. P) Write a JDBC Code for which makes use of DSN of Excel sheet and select the data. import java.sql.*; //import sun.jdbc.odbc.JdbcOdbcDriver; import java.util.*; class prt { public static void main(String args[])throws Exception { //step-1 40 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 // JdbcOdbcDriver jd=new JdbcOdbcDriver(); //DriverManager.registerDriver(jd); //explicit Registration Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); System.out.println("Driver registered"); //Step-2 Connection con=DriverManager.getConnection("jdbc:odbc:xldsn"); //Step-3 int eno=Integer.parseInt(args[0]); Scanner s=new Scanner(System.in); System.out.println("enter emp mumber"); String s1=s.nextLine(); //step-3 Statement st=con.createStatement(); //step-4 ResultSet rs=st.executeQuery("select * from [emp$] where empno="+eno); //step-5 if(rs.next()) { String empno=rs.getString(1); String ename=rs.getString(2); String sal=rs.getString(3); System.out.println("emp name="+empno); System.out.println("emp job="+ename); 41 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 System.out.println("emp sal="+sal); } else { System.out.println("no record found"); } rs.close(); st.close(); con.close(); } } Note: We can’t perform update, insert, delete in MS Excel. Dealing with CSV file: CSV file: CSV file stands for comma separated value. Sathya.csv(Sathya.txt) Stno,sname,marks 10 , Siva, 99 20 , Bhargav 100 30, Reddy 98 CSV file is one of the text file to be created in text editors(note pad, notepad ++) e.t.c., and it must be saved on some file name with an extension eiter .csv or .txt CSV file contains multiple rows treated as records and those record values must be separated by coma (,). Since we are creating the file either in notepad or notepad ++ e.t.c. there is no specific driver so that we need to use Type-1 driver to retrieve the data from CSV file by creating DSN (Choose Microsoft Text Driver (*.txt, *.csv). P) Write a Program for Data retrieval for CSV file. 42 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 import java.sql.*; import java.util.*; class sturec { public static void main(String args[])throws Exception { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); System.out.println("Driver registered"); Connection con=DriverManager.getConnection("jdbc:odbc:csv"); Statement st=con.createStatement(); ResultSet rs=st.executeQuery("select * from sturec.csv"); while(rs.next()) { System.out.println(rs.getString(1)+" "+rs.getString(2)); } rs.close(); st.close(); 43 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 con.close(); } } Note: We can’t perform insert, delete, update operations on CSV file. Pre Compiled or Dynamic Queries: In our earlier applications what are all queries we have submitted through the Statement interface Object to the Database software are known as Static queries. While the static queries are executing in the Database software they participated in three phases they are 1. Parsing Phase 2. Compilation Phase 3. Execution Phase Parsing Phase: 1. 2. 3. 4. 5. In Parsing Phase the Token of the query (Token means separating the query that means insert, into e.t.c.,) is known as splitting or parsing phase. In compilation Phase syntactical errors of will be checked by the Database engines. Executing the query phase is nothing but obtaining the result from the Database software. Whenever we submit same query multiple times through the Statement interface Object then the same query participates in parsing phase and compilation phase which is not a recommended process. Because it takes more amount of time for parsing and compilation phases and leads Lack of Performance. To avoid these problems it is highly recommended to use the concept of Dynamic/ Pre compiled queries. Static Query def: A static query is one which always participates in repeatedly in parsing, compilation and execution phase (OR) If any query executed through Statement interface Object then such type of queries we knew as static queries. Definition of Dynamic queries: A dynamic query is one which always participates in only once in parsing and compilation phase and repeatedly in execution phase. (OR) If any query is submitted to the Database by using PreparedStatement interface then those queries are known as Dynamic/precompiled queries. 44 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 Hence industry is not recommended to execute the same type of query with Statement interface and it is highly recommended to execute the same type of the query multiple times with help of PreparedStatement interface. Steps and guidelines to executing Precompiled/Dynamic queries: 1. Prepare a dynamic query EX: String qry1=”insert into emp values(?,?,?) String qry2=”Select * from emp”; 2. Here ? (question marks) are known as place holders/indexed/positional parameters and whose numbers start from 1,2,----,n from left to right Associativity. 3. Create an Object of PreparedStatement interface for executing dynamic queries to create Object of PreparedStatement. We use the following method which is present in Connection interface. Public PrepatedStatement PreparedStatement(String) Here the parameter String represents name of the Dynamic query in Step-1. EX: PrepatedStatement ps = con.preparedStatement(qry1). Here PrepatedStatement is the sub interface of Statement interface. So that all the methods of Statement interface are inherited into PreparedStatement. Here ps is the indirect Object of Prepared interface and it is one of the direct Object of sub class of PreparedStatement interface. 4. Set values for positional parameters. Set the values for the positional parameters we use the following generalized method present in PreparedStatement. java.sql.PreparedStatement public void setXxx(int position number, xxx value); Here xxx represents Fundametal and String datatype. EX: ps.SetInt(60) Ps.SetString(2,’Sathya’) Execute select and non select dynamic queries. To execute these queries we use following methods. 45 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 java.sql.PreparedStatement a) b) c) 5. Public int executeUpdate() Public ResultSet executeQuery() Public boolean execute() int res=ps.executeUpdate(); if(res>0) { System.out.println(res+”row inserted”); } else { System.out.println(“record not inserted”); } 6. Close or terminate all the JDBC stream Objects associated with dynamic queries. EX: rs.close(); ps.close(); con.clsoe(); EX: import java.sql.*; import java.util.*; class jdbc90 { public static void main(String args[]) throws Exception { Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger"); //Prepare the dynamic query 46 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 String qry="select * from emp where empno=?"; PreparedStatement ps=con.prepareStatement(qry); //set the values for the positional paramerters ps.setInt(1,9999); //Create dynamic select query ResultSet rs=ps.executeQuery(); if(rs.next()) { String empno1=rs.getString(1); String ename1=rs.getString(2); System.out.println(empno1+" "+ename1); while(rs.next()) { String empno=rs.getString(1); String ename=rs.getString(2); System.out.println(empno+" "+ename); } } else { 47 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 System.out.println("No Record found"); } rs.close(); ps.close(); con.close(); } } //Write same program with String Positional Parameter import java.sql.*; import java.util.*; class jdbc90 { public static void main(String args[]) throws Exception { Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger"); //Prepare the dynamic query String qry="select * from emp where ename like ?"; PreparedStatement ps=con.prepareStatement(qry); //set the values for the positional paramerters 48 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 ps.setString(1,"S%"); //Create dynamic select query ResultSet rs=ps.executeQuery(); if(rs.next()) { String empno1=rs.getString(1); String ename1=rs.getString(2); System.out.println(empno1+" "+ename1); while(rs.next()) { String empno=rs.getString(1); String ename=rs.getString(2); System.out.println(empno+" "+ename); } } else { System.out.println("No Record found"); } rs.close(); 49 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 ps.close(); con.close(); } } /*Observations: Here we have to observe the positional parameters. In this program no need to keep postional String parameters in single quotes*/ P) Write a JDBC Program which will insert number of records in the dept Database by accepting dept number, dname and location from the keyboard by using PreparedStatement. import java.sql.*; import java.util.*; class practicedemo { public static void main(String args[]) throws Exception { Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger"); String qry="insert into dept values(?,?,?)"; PreparedStatement ps=con.prepareStatement(qry); Scanner s=new Scanner(System.in); 50 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 System.out.println("enter dept number"); int DEPTNO=Integer.parseInt(s.nextLine()); System.out.println("Enter dept name"); String DNAME=s.nextLine(); System.out.println("Enter location"); String LOC=s.nextLine(); //set the values for positional parameters ps.setInt(1,DEPTNO); ps.setString(2,DNAME); ps.setString(3,LOC); //executing Dynamic query insertion int res=ps.executeUpdate(); if(res>0) { System.out.println(res+"row inserted"); } else { System.out.println("Record not inserted"); } //close all Objects ps.close(); 51 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 con.close(); } } P) Write a JDBC Program which will list employee name and employee designation and their numbers and whose salary list between 1000 and 3000. import java.sql.*; import java.util.*; class jdbc90 { public static void main(String args[]) throws Exception { Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger"); //Prepare the dynamic query String qry="select empno,ename,job,sal from emp where sal between ? and ?"; PreparedStatement ps=con.prepareStatement(qry); //set the values for the positional paramerters ps.setFloat(1,1000.0f); ps.setFloat(2,2000.0f); //Create dynamic select query ResultSet rs=ps.executeQuery(); if(rs.next()) 52 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 { String empno1=rs.getString(1); String ename1=rs.getString(2); System.out.println(empno1+" "+ename1); while(rs.next()) { String empno=rs.getString(1); String ename=rs.getString(2); System.out.println(empno+" "+ename); } } else { System.out.println("No Record found"); } rs.close(); ps.close(); con.close(); } } P) Write a Java Program which will copy the Excel Sheet Database to the Oracle Database. import java.sql.*; 53 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 class practicedemo { public static void main(String args[])throws Exception { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Class.forName("oracle.jdbc.driver.OracleDriver"); Connection xcon=DriverManager.getConnection("jdbc:odbc:xldsn"); System.out.println("connection obtained from Excel"); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger"); System.out.println("connection obtained from Oracle"); Statement st=xcon.createStatement(); PreparedStatement ps=con.prepareStatement("insert into student values(?,?,?)"); //get the data from excel ResultSet rs=st.executeQuery("select * from [student$]"); //insert the excel record into Oracle while(rs.next()) { String sno=rs.getString(1); String sname=rs.getString(2); String address=rs.getString(3); ps.setString(1,sno); ps.setString(2,sname); ps.setString(3,address); 54 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 int res=ps.executeUpdate(); System.out.println(res+"row inserted"); } System.out.println("Data Transfered from excel to Oracle"); rs.close(); ps.close(); st.close(); con.close(); xcon.close(); } } Note: To execute the above Java program the Java programmer must follow the following pre requisites. 1. Create the Worksheet and rename the worksheet as student. 2. Ensure we must create a DSN for Excel worksheet. 3. Ensure the Java programmer must use Type-1 Driver for retrieving the data from Excel because it is one of the unsecured. 4. As per Oracle Database concerned, the Java programmer must create student table with the same columns like Excel and use Type-4 driver to interact with Oracle Database. Differences between Statement and PreparedStatement Statement PreparedStatement 1. Statement is one of the super interface 1. PreparedStatement is one of the sub for the PreparedStatement interface. interface for the Statement interface. 2. What are all queries submitted through 2. What are all queries submitted through the Statement interface such queries are the PreparedStatement interface such known as static queries. queries are known as dynamic or precompiled queries. 3. Queries of Statement interface 3. Queries of PreparedStatement interface participates repeatedly in parsing and only once in participating compilation compilation phase. phase. 55 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 4. Statement interface object is highly recommended to execute different types of queries at different times. 5. The data of static queries of Statement interface participates in both parsing and compilation phase. 4. PreparedStatement interface Object is highly recommended to execute same type of query multiple times. 5. The data of dynamic queries of PreparedStatement participating only at execution phase. Stored Procedures: In JDBC application development so for we executed all the queries either by using Statement interface or by using PreparedStatement interface. Each and every JDBC application belongs to either 2 ties or 3 tier application. A JDBC 2 tier application contains two categories of programs they are a) Java program b) Database Software a) Java Program: A Java program is always treated as a Client Program. And by default it contains the following logics. i. Presentation Logic ii. Persisting Logic. iii. Business Logics. i. Presentation Logic: Presentation Logic always gives physical visualization of the application regarding input and output. EX: The block of Statements which write for accepting stdno, sname and three subjects marks on the console is comes under presentation logic. ii. Persistence Logic: Persistence Logic contains set of queries insert, update, delete, select on various Database operations. EX: The block of Statements we write inserting sno, sname and three subject marks into the Database comes under persisting logic. iii. Business Logic: Business logic contains accepting the input and performs some calculations. In general depends on the input if we are able to give appropriate output then it is known as business logic. EX: The block of statements which will accept three subjects marks and calculates the total and decides the grade is comes under business logic. Hence by default any Java program contains the above three logics then it is known as Fat client applications. 56 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 Database Software: Database software is not containing any specified logic(in earlier application development). These type of Database software is known as Thing server. In other words every JDBC 2 tier architecture application is containing two layers/sub architectures they are 1. Fat client/ Thin server 2. Thin client/ Fat server. Limitations of Fat client/ thin server architecture: 1. To and Pro calls are more between Java program and Database software. 2. Network traffic flow is more. 3. Performance of JDBC application is renewed. To avoid the above limitation we use revised architecture called thin client fat server application. What are all queries we executed with Statement interface and PreparedStatement interface such applications satisfies fat client/thin server architecture. To develop thin client/fat server architecture related application development we need to use of a Predefined interface called java.sql.CallableStatement. A thin Client always contains presentation logic only. A fat server always contains both persistency and business logic. In real world application development all the real world popular Database vendors provides concept called Stored Procedures for implementing thin client/ fat server architecture for providing significant advantages. Stored Procedure: The block of statements which deals with both persistency logic and business logic resides in the Database software in the form of a program known as a Stored Procedure. (OR) A set of queries which deals with both persistency logic and business logic return in the form of a PL/SQL program and reside in the Database is known as Stored Procedures. These are classified into two types those are 1. Function 2. Procedure 1. Function: A Function is sub program of a main program which will return either on value or one. Syntax for function: 57 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 Create or replace function <function name> (list of formal parameters if any) return <return type> as/is local variables begin block of statement(s); end; EX: Create a function in Oracle for computing sum of two numbers. create or replace function kin(a in number, b in number) return number is c number; begin C:=a+b; return c; end; P) Create a function which will compute sum, subtraction and multiplication of two numbers. create or replace function aop(a in number, b in number, d out number, e out number) return number is c number; 58 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 begin C:=a+b; d:=a-b; e:=a*b; return c; end; import java.sql.*; import java.util.*; class Jdbcpro4 { public static void main(String args[])throws Exception { Class.forName("oracle.jdbc.driver.OracleDriver"); System.out.println("Drivers loaded"); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger"); System.out.println("Connection Obtained"); Scanner s=new Scanner(System.in); System.out.println("enter first value"); String s1=s.nextLine(); System.out.println("enter second value"); String s2=s.nextLine(); System.out.println("enter Third value"); 59 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 String s3=s.nextLine(); System.out.println("enter Fourth value"); String s4=s.nextLine(); int n1=Integer.parseInt(s1); int n2=Integer.parseInt(s2); int n3=Integer.parseInt(s3); int n4=Integer.parseInt(s4); //step-1 //we must create kin() in Oracle //step-2 CallableStatement cs=con.prepareCall("{?=call aop(?,?,?,?)}"); //step-3 cs.setInt(2,n1); cs.setInt(3,n2); //step-4 cs.registerOutParameter(1,Types.INTEGER); cs.registerOutParameter(4,Types.INTEGER); cs.registerOutParameter(5,Types.INTEGER); //step-5 cs.execute(); //step-6 60 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 int res=cs.getInt(1); int res1=cs.getInt(4); int res2=cs.getInt(5); System.out.println("result="+res); System.out.println("result="+res1); System.out.println("result="+res2); cs.close(); con.close(); } } OUTPUT Drivers loaded Connection Obtained enter first value 1 enter second value 2 enter Third value 3 enter Fourth value 4 result=3 61 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 result=-1 result=2 In the above example OUT variables represents output variables which contain the output of the function implicitly. If we won’t write it takes as IN variable. As a Java programmer we call name of the funtction( EX: aop) form the JDBC program Procedure: Procedure always returns either one or more or none. Syntax: Create or replace procedure<procedure name> list of formal parameters if any as/is Local variables Begin Block of Statements Guidelines/ steps for executing Stored procedures from JDBC application: SUN Micro system has prescribed the following guidelines for stored procedures as a part of JDBC application development. i) Prepare a call for invoking a function or procedure which resides in the Database software. Syntax: (For function call) 1 2 3, --------4 String sf=”{?=call<fun name>(?,?,?,--------,?) In the above Syntax1 Question Mark(?) -1 represents output parameter and other question marks both the syntaxes represents mixture if input and output parameters. 12 EX: String s1=”{?=Call Sum(?,?)}” ii) Create an Object of java.sql.CallableStatement for executing Stored Procedure(either function or procedure) to execute an Object of CallableStatment we use the following method. Java.sql.Connection 62 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 Public CallableStatement prepareCall(String) Here String parameter4 represents name of the Stored Procedure EX: CallableStatement cs=con.prepareStatement(S1); Here cs is an indirect Object of CallableStatement indirect Object of CallableStatement interface but it is one of the directObject of subclass of CallableStatement interface. iii) Set the values for positional parameters which are nothing but setting the input values or input parameters. EX: cs.setInt(2,10) cs.setInt(2,20) iv) Register which parameter to register the output parameters we use the following method which is present in java.sql.CallableStatement Public void registerOutputParameter(int output int ) Positional JDBC equivalant Parameters datatype EX: cs.registerOutParameters(1, Types.INTEGER) Types.INTEGER maps number datatype of Oracle into int datatype of Java. VARCHAR maps varchar of Oracle into int Datatype of Java. Types.VARCHAR maps varchar of Oracle String datatype. v) Execute the Stored Procedure to execute the Stored Procedure use the following method present in CallableStatement public boolean execute() If the Stored Procedure executes successfully then it returns true otherwise it returns false. EX: cs.execute() vi) Obtain the result of Stored Procedure which is nothing bur retrieving value form OUT parameter to retrieve the value from OUT parameter we use the following generalized method which is present in CallableStatement interface. Public xxx get Xxx(int output positional parameter number ) 63 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 Here xxx represents any fundamental datatype String and date int res=cs.getInt(1); 1 is out parameter position number. System.out.println(“sum=”+res); vii) Close or terminate all the JDBC Objects which are associated with JDBC application. cs.close() con.close() P) Write a JDBC Program which will execute a function of Oracle sum through the JDBC program. import java.sql.*; import java.util.*; class calls1 { public static void main(String args[])throws Exception { Class.forName("oracle.jdbc.driver.OracleDriver"); System.out.println("Drivers loaded"); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger"); System.out.println("Connection Obtained"); Scanner s=new Scanner(System.in); System.out.println("enter first value"); String s1=s.nextLine(); System.out.println("enter second value"); 64 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 String s2=s.nextLine(); int n1=Integer.parseInt(s1); int n2=Integer.parseInt(s2); //step-1 //we must create kin() in Oracle //step-2 CallableStatement cs=con.prepareCall("{?=call kin(?,?)}"); //step-3 cs.setInt(2,n1); cs.setInt(3,n2); //step-4 cs.registerOutParameter(1,Types.INTEGER); //step-5 cs.execute(); //step-6 int res=cs.getInt(1); System.out.println("result="+res); cs.close(); con.close(); } } OUTPUT: C:\>javac calls1.java 65 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 C:\>java calls1 Drivers loaded Connection Obtained enter first value 2 enter second value 3 result=5 NOTE: While we are executing stored procedures it is recommended to use Type-4 drivers but not Type-1 drivers because Type-4 driver development takes care by Database vendors and they supports to execute their Stored Procedures. P) Write a procedure which will accept student number, student name and marks in three subjects. This procedure calculates Total marks and it will decide result(result=pass provided student should secure minimum 40 in each subject otherwise result fail) This procedure must also store student no, student name, thress subjects marks, total marks and result in a table called student. create or replace procedure result(sno number, sname varchar, m1 number,m2 number, m3 number, tot out number, res out varchar) as begin tot:=m1+m2+m3; if((m1<40)or (m2<40) or (m3<40)) then res:='fail'; else res:='pass'; end if; insert into student values(sno ,sname , m1,m2,m3,tot,res); 66 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 end; / P) Write a JDBC program which illustrate the concept of executing the procedure or a JDBC program must accept stdno, sname, marks in three subjects and result obtain total marks and result. import java.sql.*; import java.util.*; class Jdbcpro { public static void main(String[] args)throws Exception { Class.forName("oracle.jdbc.driver.OracleDriver"); System.out.println("Orcle driver loaded"); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger"); System.out.println("Connection obtained form Oracle"); Scanner s=new Scanner(System.in); System.out.println("Enter student number"); int sno=Integer.parseInt(s.nextLine()); System.out.println("Enter student name"); String sname=s.nextLine(); System.out.println("Enter marks in sub1"); int m1=Integer.parseInt(s.nextLine()); System.out.println("Enter marks in second subject"); int m2=Integer.parseInt(s.nextLine()); 67 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 System.out.println("Enter marks in Third subject"); int m3=Integer.parseInt(s.nextLine()); //step-1 // We should create procedure result in Database //step-2 CallableStatement cs=con.prepareCall("{call result(?,?,?,?,?,?,?)}"); //step-3 cs.setInt(1,sno); cs.setString(2,sname); cs.setInt(3,m1); cs.setInt(4,m2); cs.setInt(5,m3); //step-4 cs.registerOutParameter(6,Types.INTEGER); cs.registerOutParameter(7,Types.VARCHAR); //step-5 cs.execute(); //step-6 int tot=cs.getInt(6); String res=cs.getString(7); System.out.println("total marks="+tot); System.out.println("result="+res); //step-7 68 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 cs.close(); con.close(); } } OUTPUT: C:\>java Jdbcpro Orcle driver loaded Connection obtained form Oracle Enter student number 10 Enter student name 99 Enter marks in sub1 98 Enter marks in second subject 99 Enter marks in Third subject 0 total marks=197 result =fail Create a function which will accept employee number and percentage of salary to be hike salary to be updated in the Database and it should be returned to the JDBC application. create or replace function result1(eno number, hike number) 69 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 return number as sal1 number; begin select sal into sal1 from emp where empno=eno; sal1:=sal1+(sal1*hike); update emp set sal=sal1; return sal1; end; import java.sql.*; import java.util.*; class Jdbcpro { public static void main(String[] args)throws Exception { Class.forName("oracle.jdbc.driver.OracleDriver"); System.out.println("Orcle driver loaded"); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger"); System.out.println("Connection obtained form Oracle"); Scanner s=new Scanner(System.in); System.out.println("Enter employee number"); int eno=Integer.parseInt(s.nextLine()); 70 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 System.out.println("Enter hiked sal"); int hike=Integer.parseInt(s.nextLine()); //step-1 // We should create procedure result in Database //step-2 CallableStatement cs=con.prepareCall("{?=call res1(?,?)}"); //step-3 cs.setInt(2,eno); cs.setInt(3,hike); //step-4 cs.registerOutParameter(1,Types.FLOAT); //step-5 cs.execute(); //step-6 float sal=cs.getFloat(1); Statement st=con.createStatement(); ResultSet rs=st.executeQuery("select * from emp"); if(rs.next()) { String empno=rs.getString(1); String ename=rs.getString(2); 71 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 int sal1=rs.getInt(5); System.out.println(empno+" "+"employee number"); System.out.println(ename+" "+"employee name"); System.out.println(sal1+" "+"salary"); } //step-7 rs.close(); st.close(); cs.close(); con.close(); } } /*OUTPUT Orcle driver loaded Connection obtained form Oracle Enter employee number 7788 Enter hiked sal 1 7788 employee number CLERK employee name 11632 salary 72 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 */ Q) What is the purpose of the Type class? A) Types class is one of the predefined class present in java.sql.* package. This class contains all the JDBC equivalent data types in the form of public static final int data members. The purpose of Types class is mapping the Database datatypes into Java data types and Java data types into Database data types the following table gives mapping process. Java Datatype 1. int 2. float 3. char 4. boolean 5. String JDBC Equivalent Datatype Types.INTEGER Types.FLOAT Types.CHAR Types.BOOLEAN Types.VARCHAR Database Datatype number(7) number(7,2) char -------------Varchar2 Netbeans IDE: Vendor: SUN Micro system Version : 6.7,7.0 also Source code: open source Download: www.netbeans.com No additional settings required Metadata: Data about Data is known as Metadata. In JDBC Programming Metadata concept disvided into three types they are i) Database Metadata ii) ResultSet Metadata iii) Parameter Metadata. 1. Database Metadata: Database Metadata always deals with underline Database (Type of Database we use) it deals universal Database details. Some of the Universal Database details are a) Finding the Database product name. b) Finding the Database product version c) Finding the Database product major version d) Finding the Database product minor version e) Finding the name of driver 73 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 f) Finding the Driver major version g) Finding the Driver minor version. In order to find Database Metadata we need to create an Object java.sql.Database Metadata. Database Metadata details can be obtained when the connection Object is successfully created. To create an Object of Database Metadata we use the following method which is present in Connection interface. Java.sql.Connection Public Database Metadata getMetadata EX: Database Metadata dmd.con.getMetadata Methods in Database Metadata interface: i. Public String getDatabase productName() ii. Public String getDatabaseProductVersion() iii. Public String getDatabaseProductMajorVersion() iv. Public String getDatabaseMinorVersion v. Public String getDriverName() vi. Public String getDriverVersion() vii. Public String getDriverMajorVersion() viii. Public String getDriverMinorVersion() P) Write a Java program which illustrates the concept of Database Metadata. import java.sql.*; class frt { public static void main(String args[])throws Exception { Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger"); DatabaseMetaData dm=con.getMetaData(); System.out.println("Database Product name is="+dm.getDatabaseProductName()); System.out.println("Database Product Versio="+dm.getDatabaseProductVersion()); 74 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 System.out.println("Driver Name="+dm.getDriverName()); System.out.println("Driver Version="+dm.getDriverVersion()); System.out.println("Driver Major Version="+dm.getDriverMajorVersion()); System.out.println("Driver Minor Version="+dm.getDriverMinorVersion()); } } /*OUTPUT Database Product name is=Oracle Database Product Versio=Oracle Database 10g Enterprise Edition Release 10.2.0.1. 0 - Production With the Partitioning, OLAP and Data Mining options Driver Name=Oracle JDBC driver Driver Version=10.2.0.1.0 Driver Major Version=10 Driver Minor Version=2 */ 2. ResultSet metadata: ResultSet metadata always deals with user defined Databased(emp, dept, student e.t.c.,) or deals with details about tables which are created in universal Database details about table are nothing but 1. 2. 3. 4. Finding the name of a table by passing the columns present in a table. Finding the column types of Database and equivalent JDBC type Finding the display size of the column name. Finding the column names e.t.c., ResultSet metadata details we must create an Object details of java metadata. ResultSet metadata details can be obtained when ResultSet Object is created because it contains details about the table. 75 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 ResultSet rs=st.executeQuery(“select * from dept”); In order to create an Object of ResultSet Metadata we use the following method which is present in ResultSet interface. ResultSet ResultSet Metadata getMetadata() EX: ResultSetMetaData rsmd=rs.getMetaData() 1) Public int getColumnCount():This method is used for obtaining total number of columns which are present in a table. 2) Public String getColumnName(int): 3) Public String getColumnLablel(int): These methods are used for obtaining column name of the Database by passing column number(Starts from 1,2,-----,n) 4) Public int getColumnType(int): This method is used for obtaining JDBC equivalent type of Database column name by passing column number. 5) Public String getColumnTypeName(int): This method is used for obtaining Database Datatype of that particular column by passing column number. 6) Public int getColumnDisplaySize(int): Which will display the column displaying size. P) Write a JDBC application which illustrates the concept of ResultSet Metadata. Hint: To execute any DDL statement we use the execute () of Statement interface. import java.sql.*; import java.util.*; class Jdbcex2 { public static void main(String args[])throws Exception { Class.forName("oracle.jdbc.driver.OracleDriver"); System.out.println("Driver loaded"); 76 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger"); Statement st=con.createStatement(); ResultSet rs=st.executeQuery("select * from "+args[0]); ResultSetMetaData rsmd=rs.getMetaData(); int noc=rsmd.getColumnCount(); System.out.println("number of columns="+noc); for(int i=1;i<=noc;i++) { String cname=rsmd.getColumnName(i); String dtype=rsmd.getColumnTypeName(i); int jdbctype=rsmd.getColumnType(i); int size=rsmd.getColumnDisplaySize(i); System.out.println(cname+" "+dtype+" "+jdbctype+" "+size); } rs.close(); con.close(); } } P) Write a JDBC application which will display complete table that is records with Column names. import java.sql.*; import java.util.*; 77 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 class Jdbcex2 { public static void main(String args[])throws Exception { Class.forName("oracle.jdbc.driver.OracleDriver"); System.out.println("Driver loaded"); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger"); Statement st=con.createStatement(); ResultSet rs=st.executeQuery("select * from "+args[0]); ResultSetMetaData rsmd=rs.getMetaData(); int noc=rsmd.getColumnCount(); System.out.println("------------------"); for(int i=1;i<=noc;i++) { System.out.println(rsmd.getColumnName(i)+" "); } System.out.println("\n"); System.out.println("-------------------"); //printing records while(rs.next()) { for(int i=1;i<=noc;i++) 78 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 { String s1=rs.getString(i); System.out.println(s1+" "); } System.out.println("\n"); } rs.close(); st.close(); con.close(); } } 3. Parameter MetaData: Parameter MetaData always deals with information about indexed/positional parameters such as a) Number of Positional Parameters. b) Number of input parameters c) Number of output parameters d) Input and Output parameter types of both JDBC equivalent and Database equivalent. 1. As on today most of the popular Database products are not supporting parameter Metadata because positional parameters decided by the Java programmer and specifying their types while executing dynamic queries and stored procedures. 2. But as on today the CloudSpace Organization developed Database called CloudSpace Database which will support parameter Metadata. 3. In order to get Parameter MetaData we need to create an Object of java.sql.ParameterMetadata interface. To create an Object of parameter MetaData we use the following method which is present in PreparedStatement interface and it is further inherited into CallableStatement. Public parameterMetaData getParameterMetaData() 79 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 Parameter pmd=ps.getParameterMetadata() parameterMetaData pmd=cs.getParameterMetaData(); Q) can we execute any select query without execute query? A) Yes, We can execute any select query by using the following methods. Java.sql.Statement Public boolean String(String) Java.sql.PrepatedStatement Public boolean execute() Dynamic select query After executing either static select query or dynamic select query successfully the result of the Database table is available in the main memory without having any name. If at all we are giving the name to unnamed result then it must be an Object of ResultSet interface and it can be given by calling a method called getResultSet() and whose prototype java.sql.Statement Public ResultSet getResultSet Statement st=con.createStatement(); st.execute(“select * from dept”); ResultSet rs=st.getResultSet(); PreparedStatement ps=con.PrepareStatement(“select * from dept”); ps.execute(); ResultSet rs=ps.getResultSet() P) Write a JDBC application which will execute any DDL querry. import java.sql.*; import java.util.*; class Jdbcex6 { 80 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 public static void main(String args[]) throws Exception { Class.forName("oracle.jdbc.driver.OracleDriver"); System.out.println("Drivers loaded"); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger"); System.out.println("Connection Obtained from Oracle"); Statement st=con.createStatement(); Scanner s=new Scanner(System.in); System.out.println("Enter DDL Statement"); String s1=s.nextLine(); st.execute(s1); System.out.println("DDL Execute- veriy in Oracle"); st.close(); con.close(); } } Advantages of Type-4 Drivers: 1. Type-4 drivers implemented by Database vendors in Java language so that they are always possessing platform independency. 2. Type-4 driver takes less number of two and pro calls between Java application and Database software so that network traffic flow is reduced it leads to high performance. 3. This driver is always recommended by the industry for developing large scale Database applications. 81 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 Disadvantages: 1. Type-4 driver allows developing only two tier applications but not 3 tier applications. 2. While we are using Type-4 drivers the Java programmer must ensure related jar files must be installed in the client machine. Type-2 Drivers: Advantages: 1. 2. 3. 4. Type-2 Drivers developed by Database vendors. The implementation language of Type-2 driver is mixture of Java and C. Hence Type-2 drivers always possess partial platform independency. Type-2 drivers are also known as native drivers and Type-2 drivers are highly recommended to develop small scale Database applications or standalone applications. Disadvantages: 1. Possesses partial platform independency but not complete platform independency(like Type-4) 2. With Type-2 driver we are able to develop 2 tier applications but not 3 tier applications. Summary of Type-2 driver: (Oracle Corporation) Driver Name : OracleDriver Fully Qualified Name : oracle.jdbc.driver.* Logical Name : oci8 Vendor : Oracle Corporation Jar files : Classes12.jar Ojdbc.jar Loading Type-2 Driver: EX: DriverManager.registerDriver(“new oracle.jdbc.driver.OracleDriver”) //explicit Class.forName(“oracle.jdbc.driver.OracleDriver”) //implicit 82 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 Obtaining the connection from the Database by using Type-2 Driver: Syn: Main protocol : sub protocol : Logical name of Type-2: @service id EX: jdbc: oracle : oci8 : @ orcl Connection con=DriverManager.getConnection(“jdbc:oracle:oci8:@sathya”,”scott”,”tiger”) P) Write a JDBC application which will execute all the group functions in Oracle by using Type-2 Driver. import java.sql.*; import java.util.*; class Jdbcex6 { public static void main(String args[]) throws Exception { Class.forName("oracle.jdbc.driver.OracleDriver"); System.out.println("Drivers loaded"); Connection con=DriverManager.getConnection("jdbc:oracle:oci8:@orcl","scott","tiger"); System.out.println("Connection Obtained from Oracle"); Statement st=con.createStatement(); ResultSet rs=st.executeQuery("select sum(sal),avg(sal),min(sal),max(sal),count(*),count(sal),count(distinct sal)" + " from emp"); if(rs.next()) { 83 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 System.out.println("total sal="+rs.getFloat(1)); System.out.println("average sal="+rs.getFloat(2)); System.out.println("maximum sal="+rs.getFloat(3)); System.out.println("minimum sal="+rs.getFloat(4)); System.out.println("Total number of employees="+rs.getInt(5)); System.out.println("Total number of employees salary exluding nulls="+rs.getInt(6)); System.out.println("Total duplicates="+rs.getInt(7)); number of employees salary } rs.close(); con.close(); } } /*OUTPUT Drivers loaded Connection Obtained from Oracle total sal=140990.52 average sal=11749.21 maximum sal=11749.21 minimum sal=11749.21 Total number of employees=12 Total number of employees salary exluding nulls=12 Total number of employees salary exluding nulls and duplicates=1 */ 84 exluding nulls and B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 Application Layer Database Layer Java Application Database Software 1 JDBC API 4 7 6 2 T y p e 2 5 5 5 3 Advantages: 1. We know that Type-2 driver implementation is the mixture of java and C 2. Hence it possess partial platform independency(far better than Type-1) 3. With Type-2 driver we get less number of to and pro calls and reduces network traffic flow and improves the performance. 4. Highly recommended to perform standalone Database operations. Disadvantages: 1. Possesses platform independency but not complete platform independency(like Type-4) 2. With Type-2 driver we are able to develop 2 tier applications but not 3 tier applications. 85 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 Summary of JDBC drivers: JDBC Driver Type Name Vendor Type-1 JbdcOdbc Driver Type-2 Native Database Vendors Java+C Type-3 Net protocol Server Vendors Java Type-4 All Java, pure, thin Database Vendors Java Bridge SUN Micro System Implementation Language C NOTE: All the applications upto now we have done are JDBC 2.0 from upcoming applications are JDBC 2.1 to 3.0 NOTE2: Save point is JDBC 4.0 application. Batch Processing in JDBC: It is one of the additional facility introduced in JDBC2.1 version. Batch processing always makes us to get consistent results. Need of Batch Processing: We know that whatever the queries we execute by default with a JDBC application, it is by default executed and auto committed. If we develop group of dependent transactions(queries) then those group of queries are individually visiting from Java application to Database software and there is a possibility of executing some of the transactions are not executed successfully because of this execution we can figure out(identify) the following limitations. 1. There is a possibility of leading inconsistent Database results. 2. Because of individual query execution, to and pro calls are more between Java application and Database software. So that network traffic flow is more and we get lesser performance. 3. Because of individual query execution, it may take more execution time. To solve the above problems we must use the concept of Batch processing. Advantages of Batch Processing: 1. It always provides and ensures consistent results of the Database. 2. To an Pro calls are minimized(takes only 2 To and Pro calls) 3. It provides less execution time because all dependent and independent transactions are put in the batch. 86 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 Def: The process of combining or grouping different type or similar type of DML statements in a single unit and executing in the Database software is known as Batch Processing. While we are executing both DML statements, there is a possibility of getting BatchUpdateException. When we get BatchUpdateException: BatchUpdateException is one the predefined sub exception of java.sql.SQLException whenever we submit n number of dependent transactions to the Database in the form of a batch and assume n-1 transactions are successfully executed and nth transaction is unable to execute because of network problems or Database problems then JVM rises a predefined exception called java.sql.BatchUpdateException with respective nth transaction which is unable to execute. If BatchUpdateException is generated then as rollback(undoing the changes to the original values). If no BatchupdateExcepion is coming then as a Java programmer we commit(doing the Changes to the Original Database). Batch Processing concept always deals with DML statements only but not DDL Statements. Steps for developing Batch Processing applications: 1. Begin the transaction by making auto commit as false(recommended and mandatory) to make auto commit as false we use the following method present in connection interface. java.sql.Connection public void setAutoCommit(boolean) EX: con.setAutoCommit(flase) This statement makes the Database environment to understand postpone the commitment of transaction execution until we say auto commit as true. 2. To start with Batch processing we need to create an Object of Statement interface. EX: Statement st=con.creaeStatement(); 3. Decide the group of dependent/individual DML statements and put them in a batch. To make the DML statements as batch we use the following method present in Statement interface. java.sql.Statement public void addBatch(String) Here String parameter represents DML statements(insert,update,delete). EX: st.addBatch(Update Account set bal=sal+1000 where accno=502”) 87 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 st.addBatch(Update Account set bal=3000 where accno=503”); st.addBatch(“delete from dept”); 4. Execute batch of Statements to execute the batch of statements we use the following method which is present in statement interface. Java.sql.Statement public int[] executeBatch() Array of integers the number of records affected individually in the Database software because of Database software. EX: int res=st.executeBatch() res 0 1 1 2 3 2 4 3 In order to find total number of records affected in the original Database because of Batch execution can be found by using following code segment. int s=0; { s=s+res[i]; System.out.println(“number of records affected in oiginal Database =”+s); //6 } Note: During the batch execution if one of the Statement is not executing because of condition is not satisfying then its result in the int[] is 0. It is not treated as BatchUpdat dExcception. 5. If BatchUpdateException is resulted then perform step-6 otherwise perform step-7 6. Rollback the changes to do this use the following method which is present in Connection interface. java.sql.Conenction public void rollback EX: con.rollback() 88 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 7. Since no BatchUpdateException is rise, as a Java programmer first we need to set auto commit as true and call commit() which is present in Connecton interface EX: con.setAutoCommit(true) Con.commit(); P) Write a Java program which illustrates Batch Processing? import java.sql.*; import java.util.*; class Jdbcex6 { public static void main(String args[]) { Connection con=null; Statement st=null; try { Class.forName("oracle.jdbc.driver.OracleDriver"); con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger"); con.setAutoCommit(false); st=con.createStatement(); st.addBatch("insert into student10 values(43,'doni')"); st.addBatch("insert into student10 values(32,'Kiran')"); int res[]=st.executeBatch(); 89 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 int s=0; for(int i=0;i<res.length;i++) { s=s+res[i]; } System.out.println("number of rows affected="+s); con.setAutoCommit(true); con.commit(); } catch(BatchUpdateException be) { System.err.println("Problem in batch execution"); try { con.rollback(); } catch(SQLException se) { System.err.println("Database connections are not follwed"); } } catch(ClassNotFoundException ce) { 90 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 System.err.println("Class not available"); } catch(SQLException se) { System.err.println("Database connections are not followed"); } finally { try { st.close(); con.close(); } catch(SQLException se) { System.err.println("Database connections not followed"); } } } } Q) Can we write Try and Catch blocks in Catch and Finally blocks? A) Yes, In Catch and Finally blocks whenever we refer the Objects of class and interfaces in which are throwing the exceptions then such type of Objects must be always placed in within Try 91 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 and Catch blocks. Specially all the interfaces java.sql.* package (Connection, statement, PreparedStatement, ResultSet, e.t.c.,) are throwing the predefined exception called java.sql.SQL Exception. Hence we are referring these interface Objects either in Catch block or in finally block, those Objects must be written in try and catch blocks otherwise we will get Compile tine error. Q) What are the reasons for rising Batch? BatchUpdateExcception is rising because of the following conditions. a) Because of Database Software problems/failure when batch statements are executing. b) Because of Network problems implementing the following problem by using Batch Processing. Q) Why Callable Statement is not useful for executing Batch Applications? A) CallableStatement is meant for executing stored procedures resides in Database software with collection of DML Statements. P) Write above JDBC program to insert four records by using PreparedStatement. NOTE: By using PreparedStatement we can perform once one DML operation for suppose if we would like to insert four records we can insert but here we would like to update records that is not possible. We can update separately that means in separate PreparedStatement Object because PreparedStatement never participate repeatedly in parsing, compilation phase. import java.sql.*; import java.util.*; class jdbc90 { public static void main(String args[]) { Connection con=null; 92 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 PreparedStatement ps=null; try { Class.forName("oracle.jdbc.driver.OracleDriver"); con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger"); con.setAutoCommit(false); ps=con.prepareStatement("insert into student10 values(?,?)"); ps.setInt(1,22); ps.setString(2,"king"); ps.addBatch(); ps.setInt(1,23); ps.setString(2,"ring"); ps.addBatch(); ps.setInt(1,73); ps.setString(2,"sing"); ps.addBatch(); ps.setInt(1,73); 93 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 ps.setString(2,"zing"); ps.addBatch(); int res[]=ps.executeBatch(); if(res.length>-1) { System.out.println("Number of rows inserted="+res.length); } con.setAutoCommit(true); con.commit(); } catch(BatchUpdateException be) { System.err.println("Problem in batch execution"); try { con.rollback(); } catch(SQLException se) 94 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 { System.err.println("Database connections are not follwed"); } } catch(ClassNotFoundException ce) { System.err.println("Class not available"); } catch(SQLException se) { System.err.println("Database connections are not followed"); } finally { try { ps.close(); con.close(); } catch(SQLException se) { System.err.println("Database connections not followed"); 95 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 } } } } P) Write a JDBC Batch Processing program by using following Tables. Acno 10 20 Name Sathya Ravi Balance 90000 20000 Acno 30 40 Name Raju Sathya Balance 40000 60000 a) Transfering `2000 from Sathya Account to Raju Account b) Transfer `2000 from Sathya to Ravi. import java.sql.*; class jdbc90 { public static void main(String args[]) { Connection con=null; PreparedStatement ps1=null; 96 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 PreparedStatement ps2=null; PreparedStatement ps3=null; PreparedStatement ps4=null; try { Class.forName("oracle.jdbc.driver.OracleDriver"); con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger"); con.setAutoCommit(false); ps1=con.prepareStatement("update acctran1 set bal=bal+2000 where accno=?"); ps1.setInt(1,30); ps1.addBatch(); ps2=con.prepareStatement("update acctran1 set bal=bal-2000 where accno=?"); ps2.setInt(1,40); ps2.addBatch(); ps3=con.prepareStatement("update acctran set bal=bal+2000 where accno=?"); 97 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 ps3.setInt(1,20); ps3.addBatch(); ps4=con.prepareStatement("update acctran set bal=bal-2000 where accno=?"); ps4.setInt(1,10); ps4.addBatch(); int res1[]=ps1.executeBatch(); int res2[]=ps2.executeBatch(); int res3[]=ps3.executeBatch(); int res4[]=ps4.executeBatch(); con.setAutoCommit(true); con.commit(); } catch(BatchUpdateException be) { System.err.println("Problem in batch execution"); try { con.rollback(); } 98 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 catch(SQLException se) { System.err.println("Database connections are not follwed"); } } catch(ClassNotFoundException ce) { System.err.println("Class not available"); } catch(SQLException se) { System.err.println("Database connections are not followed"); } finally { try { ps1.close(); ps2.close(); ps3.close(); ps4.close(); con.close(); 99 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 } catch(SQLException se) { System.err.println("Database connections not followed"); } } } } Developing Flexible applications: If we write any JDBC application with specific driver url, username and password then that JDBC application communicates with a specific Database as and when any changes has taken place in Database software it is mandatory for the JDBC programmer to do the corresponding changes even in Java program such type of JDBC application development is known as flexible application hard coded approach other words if we write any JDBC application by specifying fixed technical information of Database(Driver name, url, user name and password) then that application is known as hard coded approach. Drawbacks with Hard Coded Approach: 1. Takes more time to do the changes in the source code of JDBC applications. 2. It kills software development that takes more amount of time there is a possibility of getting inconsistent results because the current changes of Database to be taken place in all the JDBC applications otherwise inconsistency problems will be arises. 3. The above problems can be eliminated by an approach of flexible application development. 4. Flexible application development makes us to understand if we change in one place about the technical information of Database those changes reflects in all the JDBC applications without changing source code the following diagram give the overview of flexible application development. 100 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 oracle 7 1 2 Database property Driver= oracle:jdbc:odbc:OracleDriver Java application DB2 url=jdbc:oracle:thin:@localhost:1521:orcl 7 uname: scott pwd : tiger 4 MySql 7 101 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 SQL Server 6 8 Properties file: Properties file is one in which the data is organizing in the form of (key, value). EX: Student.prop/student.rbf Student no Sname Marks =1000 =Sathya ==99.9 Here (student no, sname, marks) are called keys or properties names, (1000,Sathya, 99.99) are called values. Property files always resides in secondary memory and it must be saved some file name with an extension .prop or .rbd Steps for reading the data form properties file: 1. Ensure that properties file must be created first in the text editors.(We know that properties files always resides in secondary memory) 2. Open the properties file in read mode by making use of FileInputStream class EX: FileInputStream fis=new FileInputStream(“db.prop”) 3. Create an Object of properties class. Properties is one of the predefined file present in java.util.* package and the class Object is used for obtaining the data of the properties file into main memory. EX: Properties p=new Properties(); 102 7 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 p Key, value Here p resides in heap memory 4. Load or transfer the content of Properties file into Properties class Object (from secondary memory into primary memory) I order to load the content of Properties file into the Properties class Object we use following methods present in Properties class. java.util.Propeties public void load(FileInputSteam) p.load(fis) Obtain values(Property values) to get the property values by passing the Property names, we use the following method. java.util.properties public String getProperty(String) pvalue pname (value) (key) EX: String dname=p.getProperty(“driver name”) String url=p.getProperty(“url”) String uname = p.getProperty(“uname”) 5. Use property values which are obtained in step-5 in JDBC application to communicate with any Database. 6. Close the Properties file which was opened in Step-2. EX: fis.close() P) Write a JDBC application to communicate with a specified Database. 103 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 Connection.prop containis driver = oracle.jdbc.driver.OracleDriver url = jdbc:oracle:thin:@localhost:1521:orcl uname = scott pwd = tiger tname = select * from emp import java.util.*; import java.io.*; import java.sql.*; class jdbc90 { public static void main(String args[]) { try { Properties p=new Properties(); FileInputStream fis=new FileInputStream(args[0]); p.load(fis); String driver=p.getProperty("driver"); String url=p.getProperty("url"); 104 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 String uname=p.getProperty("uname"); String pwd=p.getProperty("pwd"); Class.forName(driver); Connection con=DriverManager.getConnection(url,uname,pwd); Statement st=con.createStatement(); ResultSet rs=st.executeQuery("select * from emp"); while(rs.next()) { String empno=rs.getString(1); String job=rs.getString(2); String mgr=rs.getString(3); System.out.println(empno+" "+job+" "+mgr); } st.close(); con.close(); } catch(FileNotFoundException fe) { System.err.println("File not available"); } catch(ArrayIndexOutOfBoundsException ae) 105 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 { System.err.println("Please enter file properties file"); } catch(ClassNotFoundException ce) { System.out.println("Class is not available"); } catch(SQLException se) { System.err.println("Connections are not followed"); } catch(Exception e) { System.err.println(e.getMessage()); e.printStackTrace(); } } } Note: Industry always recommended developing all the JDBC related applications with flexible approach but not with hard coded approach. Observation: To perform any flexible application we have to use Class.forName() otherwise we will get compile time error. Types of ResultSet: ResultSet is one of the predefined interface present in java.sql.* package and whose Object is used for holding the number of records return by the select query. We know that ResultSet interface Object can be obtained in three ways they are 106 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 1. executeQuery(-) of Statement interface. EX: ResultSet rs=st.executeQuery(“select * from dept”); 2. executeQuery() of PreparedStatement. EX: PreparedStatement ps=con.prepareStatement(“select * from dept”); ResultSet rs=ps.executeQuery(); 3. execute() of both Statement and PreparedStatement interfaces. EX: st.execute(“select * from dept”); ResultSet rs=st.getResultSet(); PreparedStatement ps=con.prepareStatement(“select * from dept”); ps.execute(); ResultSet rs=ps.getResultSet(); All these ResultSet interface Objects are allowing to retrieve data only in forward direction but not in backward direction and such ResultSets are known as non scrollable ResultSets. Which are available in JDBC2.0 based on direction of retrieval and modification as part of JDBC 2.2 ResultSets are classified into four types they are 1. 2. 3. 4. 1. Non- Scrollable ResultSets Scrollable ResultSets Read-only ResultSets Updatable ResultSets Non-Scrollable ResultSets: A non scrollable ResultSet allows us to retrieve the records in forward direction but not in backward direction and random retrieval. 2. Scrollable ResultSet: Scrollable ResultSet allows us to retrieve the records either in forward or backward direction 3. Read-only ResultSet: Read-only ResultSets are those whose changes never taken place but original Database changes occurs in ResultSet. 4. Updatable ResultSet: Updatable ResultSets are those which objects are permitting to have the changes both in ResultSet and Database that is whatever the changes we do in ResultSet that are reflecting to original Database and original Database changes are reflecting to ResultSet hence both ReadOnlyResultSets and UpdatableResultSets are treated as scrollable ResultSets. 107 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 In order to develop non scrollable, scrollable, Readonly, Updatable ResultSets are use the following datamembers present in java.sqi.ResultSet interface. Data members: 1. Public static final int TYPE-FORWARD_ONLY 2. Public static final int TYPE_SCROLL_INSENSITIVE 3. Public static final int TYPE_SCROLL_SENSITIVE Here these Datamembers are called mode value. 4. Public static final int CONCUR_READ_ONLY 5. Public static final int CONCUR_UPDATABLE Here these Datamembers are called concur value. The default data members are 1 and 4. 1. Public static final int TYPE-FORWARD_ONLY: This datamember allows us to retrieve the data from ResultSet only in forward direction. 2. Public static final int TYPE-SCROLL_INSENSITIVE: This datamember represents modifications of ResultSet object. It never occur in Original Database. 3. Public static final int TYPE_SCROLL_SENSITIVE: This datamember represents changes of ResultSet permitted to occur in the original Database. 4. Public static final int CONCUR_READ_ONLY: This datamember represents Database never permits changes of ResultSet object. 5. Public static final int CONCUR_UPDATABLE: This datamember represents Database permits to have changes of ResultSet Object. 1. Write a Statement to create non-scrollable ResultSet EX: Statement st=con.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet CONCUR_READ_ONLY) ResultSet rs=st.executeQuery(“select * from emp”); Here rs represents non scrollbale ResultSet. 2. Write a Statement for Preparing ReadOnlyResultSet 108 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 EX: Statement st=con.createStatement(ResultSet ResultSet, CONCUR_READ_ONLY) TYPE_SCROLL_INSENSITIVE, ResultSet rs=st.executeQuery(“select * from emp”); Here rs is representing Read only ResultSet. 3. Write a Statement for UpdatableResultSet EX: Statement st=con.createStatement(ResultSet TYPE_SCROLL_SENSITIVE, ResultSet CONCUR_UPDATE) ResultSet rs=st.executeQuery(“select * from emp”); Here rs is called UpdatableResultSet The above 2 and 3 statements are comes under even scrollable ResultSets. Connection interface contains the following method to prepare an appropriate type of ResultSet interface Object. public statement CreateStatement(int mode, int Concurrency) mode represents 1,2,3 datamembers, concurrency represents 4,5 datamembers. Methods in ResultSet interface in JDBC 2.1: 1. public boolean previous() 2. public void first() 3. public void last() 4. public boolean isFirst() 5. public boolean isLast() 6. public void beforeFirst() 7. public void afterLast() 8. public boolean isBeforeFirst() 9. public boolean isAfterLast() 10. public int getRow() 11. public void absolute(int) 12. pubic void relative(int) 109 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 1. public boolean previous(): this method returns true provided ResultSet interface Object is having previous record it will be presenting to previous record. If no more records available it returns false. 2. public void first() 3. public void last() These methods are used for making the ResultSet interface Object pointing to the first and last record respectively. EX: res.first() res.last() 4. public boolean isFirst() 5. public boolean isLast() These methods are used for checking whether the ResultSet object is pointing first or last records in other words method4 and 5 returns true provided ResultSet interface Object is pointing to first and last records respectively. Otherwise it returns false. EX: rs.first() boolean b1=rs.isFirst() System.out.println(b1) //true b1=rs.isLast() System.out.println(b1); //false EX2: rs.last() boolean b1=rs.isFirst(); System.out.println(b1); //false b1=rs.isLast() System.out.println(b1); //true 6. public void beforeFirst() 7. public void afterLast() These methods are used for making the ResultSet object pointing to either before first or afterLast for retrieving the records either in forward or backward direction. 110 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 8. public boolean isBeforeFirst() 9. public boolean isAfterLast() These methods returns true provided ResultSet interface is pointing either before first or after last respectively. Otherwise methods returns false. EX: rs.beforeFirst(); //by default boolean b1=rs.isBeforeFirst() System.out.println(b1); //false rs.afterLast() boolean b1=rs.isBeforeFirst() System.out.println(b1); //false b1=rs.isAfterLast() System.out.println(b1); //true 10. public int getRow(): This method is used for obtaining the record number where ResultSet interface object is pointing. 11. public void absolute(int): This method is used for making the ResultSet object to point to a particular record by visiting either forward direction or backward direction depends on type of int value we enter. If int value is positive then ResultSet interface object moves in forward direction with respective to first record. If int value negative then ResultSet interface object moves in backward direction with respect to last record. 12. pubic void relative(int): This method is used for making the ResultSet interface object to a specific record by moving forward direction or backward direction with respective to current record depends on type of int value. If int value is positive then ResultSet object moves in forward direction with respective to current record. If int value is negative then ResultSet interface Object moves in backward direction with respect to record. While we are applying methods 11 and 12 the ResultSet object must point to the record area. P) Write a JDBC application which will print the records of a table both in forward direction and backward direction and in Random retrieval. import java.sql.*; 111 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 import java.util.*; class Jdbcex61 { public static void main(String args[])throws Exception { Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger"); Statement st=con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); ResultSet rs=st.executeQuery("Select * from emp"); System.out.println("Forward Direction"); System.out.println("-----------------"); while(rs.next()) { System.out.println(rs.getString(1)+" "+rs.getString(2)); } rs.afterLast(); while(rs.previous()) { System.out.println(rs.getString(1)+" "+rs.getString(2)); } 112 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 System.out.println("-------------------------------------"); rs.first();//rs print first record System.out.println(rs.getString(1)+" "+rs.getString(2)); rs.absolute(4); //respective to fourth record. System.out.println(rs.getString(1)+" "+rs.getString(2)); rs.relative(3); //rs points sevent record System.out.println(rs.getString(1)+" "+rs.getString(2)); rs.getString(2); rs.relative(-2); //rs points 5th (7-2) record System.out.println(rs.getString(1)+" "+rs.getString(2)); rs.last(); //rs points last record that is 14 th System.out.println(rs.getString(1)+" "+rs.getString(2)); rs.relative(-4); System.out.println(rs.getString(1)+" "+rs.getString(2)); rs.last(); rs.absolute(-4); System.out.println(rs.getRow()); rs.close(); st.close(); con.close(); } 113 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 } /*OUTPUT Forward Direction ----------------7788 CLERK 101 null 7499 SALESMAN 7521 SALESMAN 7566 MANAGER 7654 SALESMAN 7698 MANAGER 7782 MANAGER 7839 PRESIDENT 7844 SALESMAN 7900 CLERK 7902 ANALYST 7902 ANALYST 7900 CLERK 7844 SALESMAN 7839 PRESIDENT 7782 MANAGER 7698 MANAGER 7654 SALESMAN 114 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 7566 MANAGER 7521 SALESMAN 7499 SALESMAN 101 null 7788 CLERK ------------------------------------7788 CLERK 7521 SALESMAN 7698 MANAGER 7566 MANAGER 7902 ANALYST 7782 MANAGER 9 */ Updatable ResultSet: Updatable ResultSets are those in which original Database modifications are reflected to ResultSet Object and ResultSet objects modifications are reflected in original Database. Q) How do you insert a record, delete a record and update a record of any Database without using SQL queries. We can do the above Database operations by making use of Updatable ResultSets. NOTE: Scorollable ResultSet fecility support by all types of JDBC drivers Updatable ResultSets are supported by Type-1 driver(SUN Micro System) and other drivers Type-2, Type3, Type-4 are not supported. 115 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 Methods present in ResultSet interface for supporting Updatable ResultSet: 1. 2. 3. 4. 5. 1. public void moveToInsertRow() public void UpdateXxx(int colon,xxx value) public void insertRow() public void deleteRow() public voiud UpdateRow() public void moveToInsertRow(): This method is used for creating an empty record cell int the ResultSet interface object that is a buffer will be creating for inserting a new record into the original Database. rs.moveToInsertRow() 2. public void UpdateXxx(int colon,xxx value): This method is one of the generalized method for updating the values in the ResultSet object. Here Xxx represents any fundamental datatype and date. 3. public void insertRow(): This method is used for inserting the record of ResultSet into the original Database. 4. public void deleteRow(): 5. public voiud UpdateRow(): These methods are used for deleting a record from ResultSet and same record will be deleted from original Database and also update values of ResultSet and they interns updates the original Database values. Steps for inserting a record into the original Database through the UpdateResultSet: 1. Call moveToInsertRow() for creating an empty buffer in ResultSet object. EX: rs.moveToInsertRow() rs Deptno 10 20 30 40 Dname Fin HR MAR ACC Loc HYD MUM BAN CHN --------------------------------------------------------------------------------------------------------------------rs.moveToInsertRow() 116 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 2. Update the column values in the ResultSet by calling UpdateXxx() EX: rs.UpdateInt(1,50) rs.UpdateString(2,”production”) rs.UpdateString(3,”Hyd”). rs Deptno 10 20 30 40 50 Dname FIN HR MAR ACC PROD Loc HYD MUM BAN CHN VJY --------------------------------------------------------------------------------------------------------------------rs.moveToInsertRow() Whatever the record is marked for insertion in ResultSet object, insert into the original Database EX: rs.InsertRow() P) Write a JDBC program which will insert a record in the dept Database by using UpdateResultSet. import java.sql.*; import java.util.*; class Jdbcinsert { public static void main(String args[])throws Exception { 117 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); Connection con=DriverManager.getConnection("jdbc:odbc:siva","scott","tiger"); Statement st=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDAT ABLE); ResultSet rs=st.executeQuery("select * from student5"); //step-1 rs.moveToInsertRow(); //step-2 Scanner s=new Scanner(System.in); System.out.println("enter sno"); int sno=Integer.parseInt(s.nextLine()); System.out.println("enter name"); String name=s.nextLine(); System.out.println("Enter gender"); String gender=s.nextLine(); rs.updateInt(1,sno); rs.updateString(2,name); rs.updateString(3,gender); //step-3 rs.insertRow(); System.out.println("Record inserted"); 118 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 rs=st.executeQuery("select * from student5"); while(rs.next()) { System.out.println(rs.getString(1)+" "+rs.getString(2)); } rs.close(); st.close(); con.close(); } } Observations; 1. 2. 3. 4. These programs may execute may not execute. It is not possible to do modifications directly on Database operations. We should use Type-1 Drivers only. There is a chance to give irrelevant output. Steps for deleting a record from the original Database through ResultSet Object: 1. Decide which record we want to remove and make ResultSet object to point rs.absolute(2); //rs points to second record 2. Call the DeleteRow method for marking the record to delete in the ResultSet object the same method will be removed form the original Database EX: rs.deleteRow P) Write a JDBC program for deleting record from the original Database through ResultSet Object. 119 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 import java.sql.*; import java.util.*; class Jdbcdelete { public static void main(String args[])throws Exception { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); System.out.println("Driver registered"); //Step-2 Connection con=DriverManager.getConnection("jdbc:odbc:siva","scott","tiger"); Statement st=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDAT ABLE); ResultSet rs=st.executeQuery("select * from student5"); //step-1 Scanner s=new Scanner(System.in); System.out.println("enter record number to delete"); int sno=Integer.parseInt(s.nextLine()); //step-2 rs.deleteRow(); System.out.println("Record deleted sucessfully"); 120 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 rs=st.executeQuery("select * from student5"); while(rs.next()) { System.out.println(rs.getString(1)+" "+rs.getString(2)); } rs.close(); st.close(); con.close(); } } Note: It is not possible to update Database original records by using UpdateResultSet we can update, delete only records which are inserted by ResultSet update. Steps for updating a record of Original Database through ResultSet object 1. Decide which record values we want to update and make ResultSet object to point to that record. EX: rs.absolute(5); //rs points fifth record 2. Update the required values of the specified record in step-1 by calling UpdateXxx(-) EX: rs.updateSting(2,”production”) Rs.updateSting(3,”Sales”); 3. Update the record of marked for updation of ResultSet into the original Database by calling updateRow() EX: rs.updateRow() P) Write a JDBC program for updating a record of original Database through ResultSet object. 121 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 import java.sql.*; import java.util.*; class Jdbcupdate { public static void main(String args[])throws Exception { Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); System.out.println("Driver registered"); //Step-2 Connection con=DriverManager.getConnection("jdbc:odbc:siva","scott","tiger"); Statement st=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDAT ABLE); ResultSet rs=st.executeQuery("select * from student5"); //step-1 Scanner s=new Scanner(System.in); System.out.println("enter record number to update"); rs.absolute(1); int sno=Integer.parseInt(s.nextLine()); //step-2 rs.updateString(2,"raju"); 122 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 rs.updateString(2,"vijay"); //step-3 rs.updateRow(); System.out.println("Record updated sucessfully"); rs=st.executeQuery("select * from student5"); while(rs.next()) { System.out.println(rs.getString(1)+" "+rs.getString(2)); } rs.close(); st.close(); con.close(); } } RowSets in JDBC 3.0: 1. RowSets are the distinct facility available JDBC 3.0 version. RowSet is the one of specialization released by SUN Microsystem for getting some significant changes in traditional JDBC programming. 2. We know that RowSet specification is nothing but set of rules given in the form of abstract methods and placed in interfaces. 3. SUN Microsystem has developed a root interface called RowSet and it is present in a predefine package called javax.sql.* in otherwords in order to deal with RowSets concept in the JDBC programming, we must import a predefined package called javax.sql.*. This package is an extension to java.sql.* while we are using RowSets in our JDBC programming, we get the following significant advantages. 123 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 i. With the single object of RowSet we are able to complete all Database operations RowSets transfers the data all at once between the multiple machines over the network round trips are reduced and improved the performance. ii. RowSet specification follows java bean properties (Java Bean is a class which contains set of setXxx(-) and set of getXxx() because of Java Bean properties satisfaction the programmer feel easy in remembering the methods. iii. RowSet specification contains Event Delegation Model. Types of RowSets: The concept of RowSet is classified into three types they are I. Cached RowSet II. JDBC RowSet III. Web RowSet All the above three are the predefined interfaces of RowSet interface and they found in a predefined package called javax.sql.*. I. i. ii. iii. Cached RowSet: Cached RowSet is one of the sub interface of RowSet. Cached RowSet is one of the disconnected RowSet. A Disconnected RowSet one which maintains the communication java application and original Database for a limited span of time but not for a longtime that is after retrieving the data form Database the connection will be disconnected form the original database and as and when changes are occurring either in RowSet or in database again connection will be obtained. The cached RowSet interface implemented by Oracle corporation in the name of OracleCachedRowSet which is present in a predefined package called Oracle.Jdbc.RowSet.* Programatically RowSet rs=new OracleCachedRowSet() or CachedRowSet crs=new CachedRowSet() Note: Even SUN Microsystem has developed an implementation class for CachedRowSet interface known as SunCachedRowSet. II. JDBC RowSet: 1. JDBC RowSet is the sub interface of RowSet interface. JDBC RowSet interface object is treated as connected RowSet. A connection RowSet is one which organizing a connection permanently from staring of the application to ending of the application. 2. The interface JDBC RowSet implemented by Oracle corporation on the name of Oracle JDBC RowSet and it is present in a predefined package called oracle.jdbc.RowSet.*. Programatically RowSet rs=new OracleJdbcRowSet(). 124 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 Note: Even Sun Microsystem has provided the implementation JDBC RowSet interface on the name of SunJdbcRowSet. III. i. ii. WebRowSet: WebRowSet is one of the interface used in servlets and jsp for implementation of web applications. Oracle corporation has provided implementation for WebRowSet the name of OracleWebRowSet present in oracle.jdbc.RowSet.* package. Conclusion: While we are using OracleCachedRowSet and OracleWebRowSet we need to set the classpath for both ocrs12.jar and ojdbc14.jar(in case of 9i) or ojdbc14.jar(in case of oracle 10g and higher versions) Methods in RowSet interface: 1. public void setURL(String) 2. public void setUname(String) 3. public void setPassword(String) 4. public void setCommand(String) 5. public boolean execute() 6. public void setConcurrency(int) 7. public void setMode(int) 8. public String getURL() 9. public String getUsetName() 10. public String getPassword() 11. public String getCommand() 12. public int getConccurency(); 13. public int getMode() P) Write a Java program which illustrates the concept of CachedRowSets. import java.sql.*; import javax.sql.*; import oracle.jdbc.rowset.*; public class Jdbcex6 { 125 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 public static void main(String args[]) { try { RowSet cr=new OracleCachedRowSet(); cr.setUrl("jdbc:oracle:oci8:@orcl"); cr.setUsername("scott"); cr.setPassword("tiger"); cr.setCommand("delete from student"); cr.execute(); System.out.println("Command executed"); while(cr.next()) { System.out.println("Connected and executed"); System.out.println(cr.getInt(1)+" "+cr.getString(2)+" "+cr.getString(3)); } cr.close(); } catch(Exception e) { System.out.println(e); } 126 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 } } EX2: Inserting a Record. import java.sql.*; import javax.sql.*; import oracle.jdbc.rowset.*; public class Jdbcex6 { public static void main(String args[]) { try { RowSet cr=new OracleCachedRowSet(); cr.setUrl("jdbc:oracle:oci8:@orcl"); cr.setUsername("scott"); cr.setPassword("tiger"); cr.setCommand("insert into stu values(10,’Siva’,’hyd’); cr.execute(); System.out.println("Command executed"); while(cr.next()) { System.out.println("Connected and executed"); 127 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 System.out.println(cr.getInt(1)+" "+cr.getString(2)+" "+cr.getString(3)); } cr.close(); } catch(Exception e) { System.out.println(e); } } } After executing above program I got the following exception. java.lang.OutOfMemoryError: This message means that for some reason the garbage collector is taking an excessive amount of time (by default 98% of all CPU time of the process) and recovers very little memory in each run (by default 2% of the heap). This effectively means that your program stops doing any progress and is busy running only the garbage collection at all time. To prevent your application from soaking up CPU time without getting anything done, the JVM throws thisError so that you have a chance of diagnosing the problem. P) Write a Java program which illustrates the concept of JdbcRowSets. import java.sql.*; import javax.sql.*; import oracle.jdbc.rowset.*; 128 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 public class jdbcrow { public static void main(String args[]) { try { JdbcRowSet cr=new OracleJdbcRowSet(); cr.setUrl("jdbc:oracle:thin:@localhost:1521:orcl"); cr.setUsername("scott"); cr.setPassword("tiger"); cr.setCommand("select * from emp student"); cr.execute(); while(cr.next()) { System.out.println(cr.getInt(1)+" "+cr.getString(2)+" "+cr.getString(3)); } } catch(Exception e) { System.err.println(e); } } 129 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 } P) Implement the following Database operations through the front end applications by using Swings. Studentinfo - Enter Student no Enter Name Enter Student Address Save Delete Sno 10 Update Select Sname Sathya Exit Address Hyderabad import javax.swing.*; import java.sql.*; import java.awt.*; import java.awt.event.*; class first extends Frame implements ActionListener { 130 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 Connection con; PreparedStatement ps1,ps2,ps3,ps4; ResultSet rs; JLabel l1,l2,l3; JTextField tf1,tf2,tf3; JButton b1,b2,b3,b4,b5; first() { setTitle("Student info"); setSize(250,250); FlowLayout fl=new FlowLayout(); setLayout(fl); setBackground(Color.pink); l1=new JLabel("Enter Student Number"); l2=new JLabel("Enter Student Name"); l3=new JLabel("Enter Student Address"); tf1=new JTextField(20); tf2=new JTextField(20); tf3=new JTextField(20); b1=new JButton("INSERT"); b2=new JButton("SELECT"); b3=new JButton("DELETE"); b4=new JButton("UPDATE"); 131 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 b5=new JButton("EXIT"); add(l1); add(tf1); add(l2); add(tf2); add(l3); add(tf3); add(b1); add(b2); add(b3); add(b4); add(b5); b1.addActionListener(this); b2.addActionListener(this); b3.addActionListener(this); b4.addActionListener(this); b5.addActionListener(this); setVisible(true); } void dbConnect() { try 132 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 { Class.forName("oracle.jdbc.driver.OracleDriver"); con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger"); String q1,q2,q3,q4; q1="insert into student11 values(?,?,?)"; q2="select * from student11 where no=?"; q3="delete from student11 where no=?"; q4="update student11 set name=?,addr=? where no=?"; ps1=con.prepareStatement(q1); ps2=con.prepareStatement(q2); ps3=con.prepareStatement(q3); ps4=con.prepareStatement(q4); } catch(Exception e) { e.printStackTrace(); } } public void actionPerformed(ActionEvent ae) { try { if(ae.getSource()==b1) 133 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 { int no; String name,addr; no=Integer.parseInt(tf1.getText()); name=tf2.getText(); addr=tf3.getText(); ps1.setInt(1,no); ps1.setString(2,name); ps1.setString(3,addr); int i=ps1.executeUpdate(); } if(ae.getSource()==b2) { int no; String name,addr; no=Integer.parseInt(tf1.getText()); name=tf2.getText(); addr=tf3.getText(); ps2.setInt(1,no); rs=ps2.executeQuery(); if(rs.next()) { 134 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 tf2.setText(rs.getString("name")); tf3.setText(rs.getString("addr")); } } if(ae.getSource()==b3) { int no; no=Integer.parseInt(tf1.getText()); ps3.setInt(1,no); int i=ps3.executeUpdate(); } if(ae.getSource()==b4) { int no; String name,addr; no=Integer.parseInt(tf1.getText()); name=tf2.getText(); addr=tf3.getText(); ps4.setString(1,name); ps4.setString(2,addr); ps4.setInt(3,no); int i=ps4.executeUpdate(); } 135 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 if(ae.getSource()==b5) { dispose(); } } catch(Exception e) { e.printStackTrace(); } } } class Jdbcex6 { public static void main(String args[]) { first f=new first(); f.dbConnect(); } } 136 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 P) Develop the following GUI application which works as a SQL editor for executing every query. SQL Editor Enter Query Dno Dname Addr 10 Sales Hyd 20 Acc Ban 30 HR Chn Result Query Execute Exit import javax.swing.*; import java.sql.*; import java.awt.*; import java.awt.event.*; 137 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 class first extends Frame implements ActionListener { Connection con; Statement st; ResultSet rs; JLabel l1,l2; JTextField tf1; JTextArea ta1; JButton b1,b2; String no; String name; String marks; String name1; first() { setTitle("Student info"); setSize(500,500); FlowLayout fl=new FlowLayout(); setLayout(fl); setBackground(Color.pink); 138 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 l1=new JLabel("Enter query"); l2=new JLabel("Result"); tf1=new JTextField(20); ta1=new JTextArea(20,20); b1=new JButton("Execute"); b2=new JButton("Exit"); add(l1); add(tf1); add(l2); add(ta1); add(b1); add(b2); b1.addActionListener(this); b2.addActionListener(this); setVisible(true); } 139 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 void dbConnect() { try { Class.forName("oracle.jdbc.driver.OracleDriver"); con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger"); st=con.createStatement(); } catch(Exception e) { e.printStackTrace(); } } public void actionPerformed(ActionEvent ae) { try { if(ae.getSource()==b1) { name1=tf1.getText(); rs=st.executeQuery(name1); 140 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 if(rs.next()) { String empno1=rs.getString(1); String ename1=rs.getString(2); ta1.append(empno1); ta1.append(ename1); while(rs.next()) { String empno=rs.getString(1); String ename=rs.getString(2); ta1.append(empno); ta1.append(ename); } } else { String str1="no record foud"; ta1.append(str1); } 141 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 } } catch(SQLException se1) { ta1.append(""); } catch(Exception e) { e.printStackTrace(); } try { if(ae.getSource()==b2) { dispose(); } } catch(Exception e) { e.printStackTrace(); } 142 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 try { if(ae.getSource()==b1) { name1=tf1.getText(); int res=st.executeUpdate(name1); int k=name1.indexOf('s'); if(k==2) { if(res>0) { String res1=String.valueOf(res); ta1.append(res1+"row inserted"); } } int z=name1.indexOf('d'); if(z==0) { if(res>0) 143 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 { String res1=String.valueOf(res); ta1.append(res1+"row deleted"); } } int m=name1.indexOf('d'); if(m==2) { if(res>0) { String res1=String.valueOf(res); ta1.append(res1+"rows updated"); } } } } catch(SQLException se) { 144 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 ta1.append("Please correct sql query"); } catch(Exception e) { e.printStackTrace(); } } } class jdbc92 { public static void main(String args[]) { first f=new first(); f.dbConnect(); } } /*OUTPUT 145 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 Dealing with Dates: Dealing with Dates in JDBC is nothing but how to store string dates of Java into Database int the form of Date Datatype of Database. The reverse process makes us to understand getting the Database Dates into String date. There are two proceures String dates of Java into Database in the form of Date type of Database. Procedure1: 1. Decide the format of the Date EX: yyyy-mm-dd. 2. Accept the String date value depends on the format decided in step-1 String s1=”2012-05-20” Convert String date of Java into java.sql.Datatype because java.sql.Date because java.sql.Date is compatable with Date datatype of Database. The following method will be use for converting String date of Java into java.sql.Date 146 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 Java.sql.Date Public String java.sql.DateValueOf(String) Here String parameter represents String date EX: java.sql.DateSd= java.sql.Date.valueOf(s1); ps.setSting(1,”yyyy-mm-dd”); ps.setDate(2,sql); Note: java.sql.Date is the sub class of java.util.Date Procedure2: 1. Decide the format and decide the value. EX: fmt=”DD-mm-yyyy” In order to convert String date into Date datatype of Database we must use the help of following class Java.text.SimpleDateFormat SimpleDateFormat(Sting fmt) Public java.util.Dateparse(String int value) EX: SimpleDateFormat sdf=new SimpleDateFormat(“DD-mm-yyyy”); Java.util.Date ud=sdf.parse(s2); 2. Convert java.util.Date int java.sql.Date by using the following API. EX: java.util.Date Public long getTime(); Java.sql.Date Java.sql.Date(long) EX: java.sql.Date sd=new java.sql.Date(ud.getTime()); ps.setString(1,”DD-mm-yyyy”); 147 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 int i=ps.executeUpdate(); After the above steps are completed a table in the Database contains as following datatype. FMT Name Yyyy-mm-Dd DD-MM-YYYY FMT Value 20-May-2012 20-May-2012 Procedure3(Reverse process): This procedure makes us to understand how to convert date type of Database into String date. Procedure3: Whenever we retrieve directly the date prompt original Database it points in standard format of Operating System(DD-mm-yyyy). But a Java programmer is interested in printing the dates of Database in their own desired format(dd-mmm-yyyy) e.t.c., In order to get in our own desited format we need to go for following steps. 1. Obtain the form of Database table EX: ResultSet rs=st.executeQuery(select * from student); While(rs.next()) { String fname=rs.getString(1); } In the above code we are retrieving the dates from Database but it comes in the format of windows understanding format that is DD-mm-yyyy but the client is interested in retrieving the dates of Database in String format according to the choice of the user DD-mm-yyyy, yyyy-mmm-DD. 2. Retrieve the dates of the Database in java.sql.Date format. EX: ResultSet rs=st.executeQuery(“select * from Date_Text”) While(rs.next()) { String fname=rs.get(1); 148 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 java.sql.fmtname(1) java.sql.DateSet=rs.getDate(2); } 3. Create an Object simple date format class by specifying user interested format EX: java.sql.SimpeDateFormat 1) Public SimpleDateFormat(String fmtName) 2) Public String format(java.util.Date) EX: simpleDateFormat=new SimpleDateFormat(dd-MM-yyyy) Format Database dates which are available in the form of java.sql.Date into String format String fmtValue=set.format(sd); (or) Java.util.Date =(java.util.Date) //Object Type casting. Before writing the program we must ensute Date_Test1 table must be created. EX: create table date_test1(date1 date,date2 date); String Date Java.util.Date Java.sql.Date Date of Datebase P) Write a JDBC application which deals with accepting the Dates in String in varieties of formats and store them in the Database in the form of Date Datatype of Database, String format in Java. //Inserting Date import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; 149 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 import java.util.Scanner; public class DateTest { public static void main(String[] args) { try { Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger"); //String qry="insert into date_test1 values(to_date('13-12-11','yy/dd/mm'),to_date('2013-12SEP','yyyy/dd/mm'))"; String qry="insert into date_test1 values(to_date(?,'yy/dd/mm'),to_date(?,'yyyy/dd/mm'))"; // String qry="insert into date_test values('is','is')"; PreparedStatement ps=con.prepareStatement(qry); ps.setString(1,"12-11-10"); ps.setString(2,"2013-12-SEP"); int res=ps.executeUpdate(); //set values for positional parameters 150 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 if(res>0) { System.out.println(res+"row inserted"); } else { System.out.println("Record not inserted"); } } catch (Exception e) { e.printStackTrace(); } } } /* create table date_test1(date1 date,date2 date); */ For Complete Program Plase refer JDBC\NetBeans7.1projects\DateTest\src\InsertDateProgram.java 151 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 P) Write a JDBC application which deals with retrieving the Dates in String in varieties of formats? import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; import java.text.SimpleDateFormat; public class DateTest1 { public static void main(String[] args) { /* Connection con=null; Statement st=null; ResultSet rs=null; ResultSet rs1=null;*/ try { Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger"); 152 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 Statement st=con.createStatement(); ResultSet rs=st.executeQuery("select * from Date_test1"); while(rs.next()) { String fname=rs.getString(1); String fvalue=rs.getString(2); System.out.println(fname+" "+fvalue); } ResultSet rs1=st.executeQuery("select * from Date_test1"); while(rs1.next()) { String fname=rs1.getString(1); java.sql.Date fdate=rs1.getDate(2); java.util.Date utildate=(java.util.Date)fdate; //Object type casting SimpleDateFormat sd=new SimpleDateFormat("yyyy-MMM-dd"); String formattedValue=sd.format(utildate); System.out.println(fname+" "+formattedValue); } } catch (Exception e) { 153 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 e.printStackTrace(); } } } /*OUTPUT 1999-09-12 00:00:00.0 1988-10-13 00:00:00.0 2013-11-12 00:00:00.0 2013-09-12 00:00:00.0 2012-10-11 00:00:00.0 2013-09-12 00:00:00.0 2012-10-11 00:00:00.0 2013-09-12 00:00:00.0 1999-09-12 00:00:00.0 1988-Oct-13 2013-11-12 00:00:00.0 2013-Sep-12 2012-10-11 00:00:00.0 2013-Sep-12 2012-10-11 00:00:00.0 2013-Sep-12 */ For complete program please refer JDBC\NetBeans7.1 projects\DateTest\src\RetrieveDateProgram.java Dealing with LOBs: So far whatever the Database applications we written they are all dealing with numerical columns, Character columns, String columns and Data columns. In some of the circumstances to store Large objects into the Database and we may also retrieve large objects from the Database in order to store or retrieve large objects form the Database must support large object and at the same time we require driver support also. For example Oracle Database supports to deal with large objects. These are classified into two types they are i. ii. i. Character Large Objects Binary Large Objects. Character Large Objects: Character Large Objects deals with bulk amount of textual messages without images. 154 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 EX: .docfiles, .txt files, .rtf files which ever Database supports Character large objects, those Databases must contain a predefined Datatype called CLOB. ii. Binary Large Objects: Binary large objects deals with images with animation, without animation. EX: .jpg, .img, .jped, .avi, .mov e.t.c., In order to deal with binary large objects we must contain a predefined Datatype called BLOD. EX: Create a table student with sno, sname, sphoto Create table student(sno number, sname varchar2(10), sphoto blob) Steps or guidelines for inserting or storing BLOBS or CLOBS: i. Locate name of the file which may be CLOB file or BLOB file by using an Object of java.io.File class. File(String) Here String parameter represents name of CLOB or BLOB file. EX: File f=new File(“waterlillis.jpeg”) File f1=new File(“resume.doc”) ii. Open the located file in step-1 in read mode by making use of FileInputStream class. EX: FileInputStream fs=new FileInputStream(f); iii. Set the values for BLOB or CLOB values for Database by using the following methods which are present in PreparedStatement. Java.sql.PreparedStatement Public void setBLOB(FileInputStream, int) Public void setCharacterStream(int, FileInputStream, int) Public void setCharacterStream(int, FileInputStream, int) 155 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 Here first int parameter represents column number of BLOB or CLOB in the Database. FileInputStream class object represents name of the BLOB which is opened in read mode. Thied int parameter represents size of the BLOB fiel or CLOB file. EX: ps.setBLOB(3,fis, (int) f.length()); ps.setBinaryStream(3,fis,(int) f.length()) execute the query which contains interesting BLOB or CLOB file. iv. Int i=ps.executeUpdate(); System.err.println(i+”row inserted”); Steps for retrieving the image from the Database: 1. Choose file name and mode and open it into write mode to the help of class for FileOutputStream class for transferring the image from Database to main memory of the computer. EX: FileOutputStream fos=new FileOutpurStream(“sathya.jpeg”) 2. Get the column value of Database which belongs to BLOB type. To obtain the BLOB type of Database column we use the following methods. EX: java.sql.ResultSet Public InputStream getBinaryStream(int) (or) Public InputStream BLOB(int) Represents column no of Database. EX: InputStream is=rs.getBinaryStream(s); Here object is pointing to the image which is stored in the Database. 3. Create a Buffer for transferring image in the form of byte by byte from Database to main memory. Single byte by byte Date transmition is taken palce, it is return recommended to take an array of byte Datatype. EX: Byte Buffer =new Buffer[2096] 156 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 (The default size of the buffer is 1024 byte, 2048, 4096 e.t.c.,) that is it will be increased with the multiples of 2. 4. Read the pixels of the image(bye by byre) from Database to main memory until end of the file is taken place. EX: while(byteread=is.read(buffer)!==-1) { Fos.write(buffer, 0 byte read) In the above code public int read(byte[]) it is one of the predefined method present in InputStream class and while functionality is it reads the total size of the image and placed in byte array and it reads pixel of the Database image until end of the file is taken palce(end of the file is indicated by -1) Public void write(byte[]) It is one of the predefined method present in FileOutputStream class and this method is used for writing individual values pixels if the Database image into the output file by fiel specifying buffer size, starting position to write and what type of pixel value we are writing. P) Write a Java application for illustrating the concept of an image into the Database and retrieving the Database. InsertingImage.java: import java.io.File; import java.io.FileInputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; public class InsertingImage { public static void main(String[] args) { 157 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 try { //step-1 File f=new File("C:\\Bluehills.jpg"); //step-2 FileInputStream fis=new FileInputStream(f); Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger"); String qry="insert into studentblob values(?,?,?)"; PreparedStatement ps=con.prepareStatement(qry); ps.setInt(1,10); ps.setString(2,"Bhargav"); ps.setBinaryStream(3,fis,(int)f.length()); int i=ps.executeUpdate(); if(i>0) { System.out.println(i+"row inserted"); } else { System.out.println("Problem in inserting row"); } } 158 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 catch (Exception e) { e.printStackTrace(); } } } /* SQL> create table studentblob(stno number(10),sname varchar2(10),sphoto blob); */ For complete program please refer JDBC\NetBeans7.1 projects\DateTest\src\InsertingImage.java RetrievingImage.java import java.io.FileOutputStream; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class RetrievingImage { public static void main(String[] args) { try { 159 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger"); FileOutputStream fos=new FileOutputStream("C:/hills.jpg"); Statement st=con.createStatement(); ResultSet rs=st.executeQuery("select * from studentblob"); InputStream is=null; if(rs.next()) { is=rs.getBinaryStream(3); } byte buffer[]=new byte[4096]; int bytesread=0; while((bytesread=is.read(buffer))!=-1) { fos.write(buffer,0,bytesread); } System.out.println("Image retrieved verify hills.jpg"); } catch (Exception e) { } } } 160 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 For Complete program please refer JDBC\NetBeans7.1 projects\DateTest\src\InsertingImage.java NOTE: The same procedure even applicable for storing and retrieving character large objects provided the following changes must be taken place in the above programs. In image insert java we write rs or ps.setCharacterStream (-,-,-) instead of ps.setBinaryStream(-,-,-) in img, ret.java we write following statement rs.getCharacterStream(-) instead of rs.getBinaryStream Recommondations: Industry not recommended to store the image in t he Database and to retrieve the images from Database because storing and retrieving into Database is time consuming process to eliminate this process industry is highly recommended to store the images in the server memory and store image location path into the Database. In JDBC programming Type-1 drivers may not be effectively supporting to deal with LOBS. Type-2, Type-3, Type-4 are the specialized by Database and server vendors are effectively dealing with Large objects both for retrieval and storing provided the Database software must contain BLOBs and CLOB as a Datatype. Q) What is the execution Status of execute() in the case of successful and unsuccessful execution of DDL and DML statements. A) Whenwe execute successfully with execute() then it returns false. Ohterwise true(un successful execution) if we execute DML statements successfully with execute() then it returns true otherwise false. Connection Pooling: Connection pooling is one of the predefined service available in the standalone applications of JBC and in server software. The connection pooling which is available in Standalone JDBC applications is programmable. Whereas the Connection pooling service available in server software is configurable. The Connection pooling concept can be utilize in standalone JDBC applications in the form of JDBC frivers. Connection Pooling def: A connectionPool is a factory method which contains readily available connection objects Connection Pooling concept available in two types they are 1. Programmable managed Connection pool 2. Predefined Connection pool 161 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 1. Programmable managed Connection pool: Connection pools are those which are created by JDBC programmer that is connections are created by programmers and managed by programmers and releasing or destructing the connection also done by programmer this type of process is not recommended. But recommended to use predefined connection pooling concept. 2. Predefined Connection pool: Predefined Connection pools are those which are either managed by JDBC drivers or managed by server softwares. That is connections creation, managing the connections and destroying the connections will be done by either JDBC drivers or Server softwares. API: The concept of Connection pooling available in JDBC in the form of two interfaces present in javax.sql.* package they are 1. Java.sql.ConnectionPoolDataSource 2. Javax.sql.PooledConnection The above interfaces are implemented by various Database vendors like IBM, Oracle e.t.c., for example Oracle Corporation has developed the following class for providing Connection pooling concept. OralceConnectionPoolDataSoruce. This is the predefined class present in Oracle,jdbc.pool.*. It is oen of the subclass of javax.sql.Datasource hence creating a connection pool is nothing but creating an object of OracleConnectionPoolDataSource. EX: OracleConnectionPoolDataSource ocp=new OracleConnectionPoolDataSource() Each and every Connection Pool is associated with a unique name called Datasource which is nothing but an object of OracleConnectionPoolDataSource. Steps for implementing JDBC application with ConnectionPooling Concept: 1. Create a Connection pool and make it to associated with a distinct DataSource name. 2. Specify the Connection parameters for creating for creating number of records available connection pool. To specify the connection parameters we use the following methods i. Public void setDriverType(String) Thin or oci8 ii. Public void setServiceName(String) localhost iii. Public void setProtNumber(int) Protno iv. Public void setUser(String) UserName v. Public void setPassword(String) Password Steps: 1. Java programmer develops a JDBC application 162 B. Siva Bhargava Reddy bhargavbsr@hotmail.com 2. 3. 4. 5. K.V.R Sir 9am JEE 8099498819 6. As a part of JDBC application programmer creates Connection pool. JDBC application request the connection pool to grant a connection Object. Connection Pool gives a Connection object to the JDBC application. JDBC application receives a Connection object from Connection pool(An object of pooled connection interface) Every JDBC application obtains physical Connection JDBC application and Database software by using an object of Pooled Connection interface that is an object PooledConenction interface(That is an Object of java.sql.ConnectionInterface) Database software extends the queries/ performs the Database operations depends on type of queries passed form JDBC applications. Database software gives the result back to the JDBC application depends on type of query executed. JDBC application receives the result form Database software and display on the console. 7. 8. 9. P) Write a Java Program which illustrate the concept of JDBC Connection Pooling. import java.sql.*; import javax.sql.*; import oracle.jdbc.pool.*; class jdbcpool { public static void main(String args[])throws Exception { //step-1 OracleConnectionPoolDataSource ds=new OracleConnectionPoolDataSource(); //step-2 ds.setDriverType("thin"); ds.setServerName("localhost"); ds.setPortNumber(1521); 163 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 ds.setServiceName("orcl"); ds.setUser("scott"); ds.setPassword("tiger"); //step-3 PooledConnection pcon=ds.getPooledConnection(); System.out.println("borrowed one Connection object from Connection pool"); //step-4 Connection con=pcon.getConnection(); System.out.println("Obtaining the connection from oracle"); //step-5 Statement st=con.createStatement(); ResultSet rs=st.executeQuery("select * from dept"); while(rs.next()) { System.out.println(rs.getString(1)+" "+rs.getString(2)); } rs.close(); st.close(); con.close(); } } Savepoint in JDBC(4.0): In the ordinary batch process either we are executing all the transactions or not executing any transactions at all that is either all the transactions are commiting or no transactions are commiting this indicates no controlling mechanism about the 164 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 transactions in order to provide transaction controlling mechanism we need to use the concept of Savepoing. DEF: A Savepoint is the breaking point with in the transactions to decide which transactions are supposed to committed and which transaction as are rollbacked. What are all transactions used before the Savepoint creation, those transaction results will be committed what are all the transactions we use after the savepoint creation their results be rollbacked. API: To deal with the concept of Savepoint we use predefined interface called java.sql.Savepoint. To create a Savepoint we use following method Java.sql.Connection Public Savepoint setSavepoint(String) Here the parameter String represents name of the Savepoint. EX: Savepoint sp=con.setSavepoint(“spt”); Let us consider the following code snippet. con.setAutoCommit(false) T1 DML Statement T2 DML Statement T3 DML Statement Savepoint sp=new Savepoint(‘so’); T4DML Statement T5 DML Statement In the above example the transactions results T1,T2,T3 are committed and the transactions results T4 and T5 will be rollback provided we must call Rollback() with respect Connection interface object by passing the reference of Savepoint. 165 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 P) Write a JDBC application which illustrates the concept of Savepoint. import java.sql.Connection; import java.sql.DriverManager; import java.sql.Savepoint; import java.sql.Statement; public class SavePoint1 { static Connection con=null; static Statement st=null; public static void main(String[] args) { try { Class.forName("oracle.jdbc.driver.OracleDriver"); con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger"); con.setAutoCommit(false); st=con.createStatement(); int i=st.executeUpdate("insert into dept1 values(23,'SE','TPT')"); System.out.println(i+"row inserted"); Savepoint sp=con.setSavepoint("spt"); int j=st.executeUpdate("update dept1 set dname='EDU' where deptno=11"); int k=st.executeUpdate("delete from dept1 where deptno=12"); System.out.println(k+"row deleted"); con.rollback(sp); con.setAutoCommit(true); 166 B. Siva Bhargava Reddy bhargavbsr@hotmail.com K.V.R Sir 9am JEE 8099498819 con.commit(); } catch (Exception e) { System.err.println("Problem in Database"); } } } /*After executing this program just observe in Database there is one row inserted and no row deleted and updated. Table is create table dept1(deptno number(5),dname varchar2(10),loc varchar2(10)); Before Running the program DEPTNO DNAME LOC ------- ---------- ---------10 SALES PLVD 11 HR KDP 12 FIN JMD 10 ACC KNL After Running the Program DEPTNO DNAME LOC -------- ---------- ---------10 SALES 11 HR PLVD KDP 167 B. Siva Bhargava Reddy bhargavbsr@hotmail.com 12 FIN 10 ACC 23 SE K.V.R Sir 9am JEE 8099498819 JMD KNL TPT */ For complete program please refer JDBC\NetBeans7.1 projects\DateTest\src\SavePoint1.java s 168