JDBC

download JDBC

of 168

description

java notes for jdbc know the connectivity

Transcript of JDBC

B. Siva Bhargava Reddy K.V.R Sir 9am JEE [email protected] 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.

JDBC APIJava Programmer 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 are7. 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 permanently9. 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.

Steps for developing a JDBC Application: 1. JDBC Drivers:

Database SoftwaresJDBC DriversJava Program

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 arei. Type1 drivers or (JDBC-ODBC bridge drivers)ii. Type2 drivers or native driversiii. Type 3 drivers or net protocol driversiv. Type 4 drivers or all java/pure/thin driversODBC 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.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.

Oracle databaseODBC Driver for Oracle

MySQL databseODBC Driver for MySQL

Paradax DatabaseODBC Driver forParadaxODBC DriversNon java java application

DB2 databaseODBC Driver forDB2

Ms AccessDatabaseODBC Driver for MsAccess

Q) What are the differences between JDBC drivers and ODBC drivers?JDBC DriversODBC Drivers

1. JDBC Drivers specification developed by SUN Micro system and JDBC drivers are implemented by Database vendors.2. All database vendors implemented JDBC Drivers in java language.3. All the JDBC drivers are Platform independent. 4. All the JDBC drivers are supplied through database softwares.5. JDBC drivers are purely meant for establishing the communication between java applications and universal softwares.

6. Industry is highly recommended to use JDBC Drivers to communicate with the database because they gives/posses platform independency.1. ODBC Drivers specification developed by Xopen and JDBC drivers are implemented by Database vendors.2. All database vendors implemented ODBC Drivers in C language.3. All the ODBC drivers are Platform dependent. 4. All the ODBC Drivers are supplied for Microsoft Operating Systems.5. ODBC Drivers are meant for both java and non java programmers for establishing communication between database softwares.6. ODBC drivers are not recommended by the industry to communication with the database because they posses/gives platform dependency.

Static Block: 1. In java library we come across various predefined classes which are present in various predefined packages. 1. 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.1. 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.1. 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"); } public static void main(String args[]) { first f=new first(); f.first(); }}OUTPUT:C:\>java stsdemoI am from execution logic staticI am from business logic staticI am from ConstructorI am from methodObservation 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"); }}class stsdemo{ static { System.out.println("Hello"); }}

OUTPUT: C:\>java stsdemoHelloException in thread "main" java.lang.NoSuchMethodError: mainP) Write a java program which illustrate the concept of static blocks.//stp.javapackage stp;public class stp{ static { System.out.println("I am from static block"); } public stp() { System.out.println("stp DC"); } public void disp() { System.out.println("STP-Disp"); }}//Stpdemo.javaimport 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) { System.err.println(args[0]+"class not exists"); } }}OUTPUT:C:\>java stpdemo stp.stpI am from static blockClass name=stp.stpArchitecture 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 software4. 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.

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 layer7. 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. Type-1 Driver allows us to develop only two-tier applications (Java application, Database Software).Note: Type: JDBC-ODBC bridgeDriver Vendor: SUN Micro SystemDriver name: sun.jdbc.odbc.JdbcOdbcDriverJar file: rt.jar(jdk 1.5, jdk 1.6/lib)Software requirement: jdk1.5/jdk 1.6Database 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 softwareSteps 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 cant 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.

Java.sql.DriverManagerPublic 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(-)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 stepsa) Created an Object of JdbcOdbc Driver classb) 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);

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 doesnt 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 : DSNHere 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 DatabaseJdbc:Odbc:AccdsnJdbc:Odbc:OradsnJdbc:Odbc:XldsnNote: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 { System.out.println("connection failed"); } }}

/* OUTPUT C:\>java Firstjdbctype-1 Driver loadingconnection 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 software4. 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.

231EX: ResultSet rs=st.executeQuery(select * from dept);rsDeptnoDnameLoc

10FinanceHyderabad

20HRDelhi

30MarketingBanglore

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.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 arei) Based on Column number or Column name in the form of String typeii) 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. public boolean next()2. public String getString(int Columnno) Columnno String3. public String getString(String Columnname) Columnname4. public xxx getXxx(int columnno) Columnno Original Type5. public xxx getXxx(String Columnname) Columnname

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);rsDeptnoDnameLoc

10FinanceHyd

20 HRBan

30MarketingChn

Obtaining the records based on column numbers.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); String dname=rs.getString(2);String loc=rs.getString(3);}Obtaining records based on columnsWhile(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 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{ 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()) { 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 7788Driver registeredenter emp mumber7788emp name=RAJUemp job=CLERKemp 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"); 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{ 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)); 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.*;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 doesnt require any DSN.Architecture: Application Layer Database Layer

Database Software 4 1 7

Java Application

JDBCJDBC API 6 5 5 5 2 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% 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 ida) Here Main Protocol is always JDBCb) 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 thind) 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) cant 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.oraEX: jdbc:oracle:thin:@localhost:1521:sathyaQ) 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.Note: Summary of OracleDriver(Type-4)Driver Name : OracleDriverFully Qualified Name: oracle.jdbc.driver.OracleDriverJar files : Class111.jar, Classes12.jarVendor Name : Oracle CorporationImplementation Language : JavaLogical 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"); System.out.println("Connection Obtained from oracle"); }}Note: We can insert like this but it is not recommended approachP) 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"); } 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); 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(); 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"); System.out.println("One record deleted sucessfully"); st.close(); con.close(); }}Q) What are the differences betweenDriverManager.registrationDriver and Class.forName(-)DriverManager.registerDriver Class.forName(-)

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.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.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(); //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(); }}/* OUTPUT C:\>java practicedemo 7788Driver registeredenter emp mumber7788emp name=RAJUemp job=CLERKemp 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 // 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); System.out.println("emp sal="+sal); } else { System.out.println("no record found"); } rs.close(); st.close(); con.close(); }}Note: We cant 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,marks10 , Siva, 9920 , Bhargav 10030, 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 .txtCSV 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.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(); con.close(); }}Note: We cant 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 are1. Parsing Phase2. Compilation Phase3. Execution PhaseParsing Phase:1. 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. 2. 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.3. 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. 4. Because it takes more amount of time for parsing and compilation phases and leads Lack of Performance. 5. 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.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 queryEX: 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.java.sql.PreparedStatementa) Public int executeUpdate()b) Public ResultSet executeQuery()c) Public boolean execute()5. 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 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 { System.out.println("No Record found"); } rs.close(); ps.close(); con.close(); } }

//Write same program with String Positional Parameterimport 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 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(); 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); 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(); 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()) { 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.*;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); 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 PreparedStatementStatementPreparedStatement

1. Statement is one of the super interface for the PreparedStatement interface.2. What are all queries submitted through the Statement interface such queries are known as static queries.

3. Queries of Statement interface participates repeatedly in parsing and compilation phase.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.1. PreparedStatement is one of the sub interface for the Statement interface.2. What are all queries submitted through the PreparedStatement interface such queries are known as dynamic or precompiled queries.3. Queries of PreparedStatement interface only once in participating 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 area) Java programb) Database Softwarea) Java Program: A Java program is always treated as a Client Program. And by default it contains the following logics.i. Presentation Logicii. 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.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 server2. 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 are1. 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: Create or replace function (list of formal parameters if any) return as/islocal variablesbegin 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; 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"); 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 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(); }}OUTPUTDrivers loadedConnection Obtainedenter first value1enter second value2enter Third value3enter Fourth value4result=3result=-1result=2

In the above example OUT variables represents output variables which contain the output of the function implicitly. If we wont write it takes as IN variable. As a Java programmer we call name of the funtction( EX: aop) form the JDBC programProcedure: Procedure always returns either one or more or none.Syntax: Create or replace procedure list of formal parameters if any as/isLocal variables BeginBlock of StatementsGuidelines/ 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, --------4String sf={?=call(?,?,?,--------,?) In the above Syntax1 Question Mark(?) -1 represents output parameter and other question marks both the syntaxes represents mixture if input and output parameters. 1 2EX: 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 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.CallableStatementPublic void registerOutputParameter(int output int )Positional JDBC equivalantParameters datatypeEX: 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 CallableStatementpublic 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 )Here xxx represents any fundamental datatype String and dateint 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"); 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.javaC:\>java calls1Drivers loadedConnection Obtainedenter first value2enter second value3result=5NOTE: 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