Vous êtes sur la page 1sur 34

JDBC ( Java Database Connectivity)

The JDBC ( Java Database Connectivity) API defines interfaces and classes for writing database applications in Java by making database connections. Using JDBC you can send SQL, PL/SQL statements to almost any relational database. JDBC is a Java API for executing SQL statements and supports basic SQL functionality. JDBC Architecture: The JDBC API supports both two-tier and three-tier processing models for database access but in general JDBC Architecture consists of two layers: 1. JDBC API: This provides the application-to-JDBC Manager connection. 2. JDBC Driver API: This supports the JDBC Manager-to-Driver Connection. The JDBC API uses a driver manager and database-specific drivers to provide transparent connectivity to heterogeneous databases. The JDBC driver manager ensures that the correct driver is used to access each data source. The driver manager is capable of supporting multiple concurrent drivers connected to multiple heterogeneous databases. Following is the architectural diagram, which shows the location of the driver manager with respect to the JDBC drivers and the Java application:

Common JDBC Components:


The JDBC API provides the following interfaces and classes: DriverManager: This interface manages a list of database drivers. Matches connection requests from the java application with the proper database driver using communication subprotocol. The first driver that recognizes a certain subprotocol under JDBC will be used to establish a database Connection.

Driver: This interface handles the communications with the database server. You will interact directly with Driver objects very rarely. Instead, you use DriverManager objects, which manages objects of this type. It also abstracts the details associated with working with Driver objects Connection : Interface with all methods for contacting a database. The connection object represents communication context, i.e., all communication with database is through connection object only. Statement : You use objects created from this interface to submit the SQL statements to the database. Some derived interfaces accept parameters in addition to executing stored procedures. ResultSet: These objects hold data retrieved from a database after you execute an SQL query using Statement objects. It acts as an iterator to allow you to move through its data. SQLException: This class handles any errors that occur in a database application. An Example Diagram Here is an example of how the core components interact in during the execution of a database query (click image to view larger version):

Java JDBC: Interaction of the core JDBC components during the execution of a database query. JDBC Driver A JDBC driver translates standard JDBC calls into a network or database protocol or into a database library API call that facilitates communication with the database. This translation layer provides JDBC applications with database independence. If the back-end database changes, only the JDBC driver need be replaced with few code modifications required. JDBC Drivers Types: JDBC driver implementations vary because of the wide variety of operating systems and hardware platforms in which Java operates.

There are four types of JDBC drivers known as: JDBC-ODBC bridge plus ODBC driver, also called Type 1. Native-API, partly Java driver, also called Type 2. JDBC-Net, pure Java driver, also called Type 3. Native-protocol, pure Java driver, also called Type 4. Type 1 JDBC-ODBC Bridge. Type 1 drivers act as a "bridge" between JDBC and another database connectivity mechanism such as ODBC. The JDBC- ODBC bridge provides JDBC access using most standard ODBC drivers. This driver is included in the Java 2 SDK within the sun.jdbc.odbc package. In this driver the java statements are converted to a jdbc statements. JDBC statements calls the ODBC by using the JDBC-ODBC Bridge. And finally the query is executed by the database. This driver has serious limitation for many applications. Functions: Translates query obtained by JDBC into corresponding ODBC query, which is then handled by the ODBC driver. Sun provides a JDBC-ODBC Bridge driver. sun.jdbc.odbc.JdbcOdbcDriver. This driver is native code and not Java, and is closed source. Client -> JDBC Driver -> ODBC Driver -> Database There is some overhead associated with the translation work to go from JDBC to ODBC.

Type 1 JDBC Architecture

Advantages: Almost any database for which ODBC driver is installed, can be accessed. Disadvantages: 1. Performance overhead since the calls have to go through the JDBC overhead bridge to the ODBC driver, then to the native database connectivity interface. 2. The ODBC driver needs to be installed on the client machine. 3. Considering the client-side software needed, this might not be suitable for applets.

Type 2 drivers use the Java Native Interface (JNI) to make calls to a local database library API. This driver converts the JDBC calls into a database specific call for databases such as SQL, ORACLE etc. This driver communicates directly with the database server. It requires some native code to connect to the database. Type 2 drivers are usually faster than Type 1 drivers. Like Type 1 drivers, Type 2 drivers require native database client libraries to be installed and configured on the client machine. Functions: 1. This type of driver converts JDBC calls into calls to the client API for that database. 2. Client -> JDBC Driver -> Vendor Client DB Library -> Database Type 2 JDBC Architecture

Advantage: Better performance than Type 1 since no jdbc to odbc translation is needed. Disadvantages 1. The vendor client library needs to be installed on the client machine. 2. Cannot be used in internet due the client side software needed 3. Not all databases give theclientsidelibrary. Type 3 Java to Network Protocol Or All- Java Driver Type 3 drivers are pure Java drivers that use a proprietary network protocol to communicate with JDBC middleware on the server. The middleware then translates the network protocol to database-specific function calls. Type 3 drivers are the most flexible JDBC solution because they do not require native database libraries on the client and can connect to many different databases on the back end. Type 3 drivers can be deployed over the Internet without client installation. (Java-------> JDBC statements------> SQL statements ------> databases.

Functions: 1. Follows a three tier communication approach. 2. Can interface to multiple databases - Not vendor specific. 3. The JDBC Client driver written in java, communicates with a middleware-net-server using a database independent protocol, and then this net server translates this request into database commands for that database. 4. Thus the client driver to middleware communication is database independent. 5. Client -> JDBC Driver -> Middleware-Net Server -> Any Database

Type 3 JDBC Architecture

Advantages 1. Since the communication between client and the middleware server is database independent, there is no need for the vendor db library on the client machine. Also the client to middleware need'nt be changed for a new database. 2. The Middleware Server (Can be a full fledged J2EE Application server) can provide typical middleware services like caching (connections, query results, and so on), load balancing, logging, auditing etc.. 3. eg. for the above include jdbc driver features in Weblogic. 4. Can be used in internet since there is no client side software needed. 5. At client side a single driver can handle any database.(It works provided the middlware supports that database!!)

Disadvantages 1. Requires database-specific coding to be done in the middle tier. 2. An extra layer added may result in a time-bottleneck. But typically this is overcome by providing efficient middleware services described above. Type 4 Java to Database Protocol. Type 4 drivers are pure Java drivers that implement a proprietary database protocol (like Oracle's SQL*Net) to communicate directly with the database. Like Type 3 drivers, they do not require native database libraries and can be deployed over the Internet without client installation. One drawback to Type 4 drivers is that they are database specific. Unlike Type 3 drivers, if your back-end database changes, you may save to purchase and deploy a new Type 4 driver (some Type 4 drivers are available free of charge from the database manufacturer). However, because Type drivers communicate directly with the database engine rather than through middleware or a native library, they are usually the fastest JDBC drivers available. This driver directly converts the java statements to SQL statements. Functions 1. Type 4 drivers are entirely written in Java that communicate directly with a vendor's database through socket connections. No translation or middleware layers, are required, improving performance. 2. The driver converts JDBC calls into the vendor-specific database protocol so that client applications can communicate directly with the database server. 3. Completely implemented in Java to achieve platform independence. 4. e.g include the widely used Oracle thin driver - oracle.jdbc.driver. OracleDriver which connect to jdbc:oracle:thin URL format. 5. Client Machine -> Native protocol JDBC Driver -> Database server Type 4 JDBC Architecture

Advantages These drivers don't translate the requests into db request to ODBC or pass it to client api for the db, nor do they need a middleware layer for request indirection. Thus the performance is considerably improved. Disadvantage At client side, a separate driver is needed for each database.

Which Driver should be used? So, you may be asking yourself, "Which is the right type of driver for your application?" Well, that depends on the requirements of your particular project If you are accessing one type of database, such as Oracle, Sybase, or IBM, the preferred driver type is 4. If your Java application is accessing multiple types of databases at the same time, type 3 is the preferred driver. Type 2 drivers are useful in situations where a type 3 or type 4 driver is not available yet for your database. The type 1 driver is not considered a deployment-level driver and is typically used for development and testing purposes only. Java Database Connectivity Steps To connect the MySQL database with the Java file. Firstly, we need to establish a connection between MySQL and Java files with the help of MySQL driver . Now we will make our account in MySQL database so that we can get connected to the database. After establishing a connection we can access or retrieve data form MySQL database. We are going to make a program on connecting to a MySQL database, after going through this program you will be able to establish a connection on your own PC. When a Java application needs to access database we have to follow the bellow Steps : 1) Load the specific JDBC driver 2) Open the connection to database which is then used to send SQL statements and get results back. 3) Create JDBC Statement object. This object contains SQL query. 4) Execute statement which returns resultset(s). ResultSet contains the tuples of database table as a result of SQL query. 5) Process the result set. 6)Close the connection. Example program import java.sql.*; public class CreateTable{ public static void main(String[] args) { System.out.println("Table Creation Example!"); Connection con = null; String url = "jdbc:mysql://localhost:3306/"; String dbName = "jdbctutorial"; String driverName = "com.mysql.jdbc.Driver"; String userName = "root"; String password = "root"; try{

Class.forName(driverName).newInstance(); con = DriverManager.getConnection(url+dbName, userName, password); try{ Statement st = con.createStatement(); String table = "CREATE TABLE Employee11(Emp_code integer, Emp_name varchar(10))"; st.executeUpdate(table); System.out.println("Table creation process successfully!"); } catch(SQLException s){ System.out.println("Table all ready exists!"); } con.close(); } catch (Exception e){ e.printStackTrace(); } } }

Statement Objects in JDBC Once a connection is obtained we can interact with the database. The JDBC Statement, CallableStatement, and PreparedStatement interfaces define the methods and properties that enable you to send SQL or PL/SQL commands and receive data from your database. They also define methods that help bridge data type differences between Java and SQL data types used in a database. Statement Statement acts like a vehicle through which SQL commands can be sent. Through the connection object we create statement kind of objects.Through the connection object we create statement kind of objects. PreparedStatement A prepared statement is an SQL statement that is precompiled by the database. Through precompilation, prepared statements improve the performance of SQL commands that are executed multiple times (given that the database supports prepared statements). Once compiled, prepared statements can be customized prior to each execution by altering predefined SQL parameters. callable statements Callable statements are used in the JDBC application to invoke PL/SQL stored procedures by means of the prepareCall() method of the Connection object created. A call to this method takes variable bind parameters as input parameters as well as output variables and creates an object instance of the CallableStatement class.

Following table provides a summary of each interface's purpose to understand how do you decide which interface to use? Interfaces Statement PreparedStatement CallableStatement Recommended Use Use for general-purpose access to your database. Useful when you are using static SQL statements at runtime. The Statement interface cannot accept parameters. Use when you plan to use the SQL statements many times. The PreparedStatement interface accepts input parameters at runtime. Use when you want to access database stored procedures. The CallableStatement interface can also accept runtime input parameters.

Working with Statement interface The java.sql.Statement interface object represent static SQL statement. It is base object type of SQL statement in java. Only one ResultSet object is associated with one Statement object. The PreparedStatement interface is the derived from it. To use Statement interface in source code, first we need to create object of Statement by calling createStatement() method. The createStatement() is available in java.sql.Connection interface. It does not take any argument. Syntax :- Statement stmt=con.createStatement() After creating object of Statement type object, we call executeUpdate() or executeQuery() method. It depends whether database is updating or result is return by SQL statement. If database is updating (Insert, Update, Delete and create) call executeUpdate() and record is fetching call executeQuery(). Syntax :- int executeUpdate("SQL Statement") esultSet executeQuery("SQL Statement") The executeUpdate() return number of rows effetcted by SQL statement and executeQuery() return the records from table based on SQL statement supplied. Here is the example of Statement interface for Insert, Update, Delete and Query record from database Here we used validations also on necessary fields like, custId and custName. SQL Statement for creating table in MySQL database Server 1 use test; 2 create table customer 3( 4 custId varchar(10) primary key, 5 custname varchar(40), 6 custaddress varchar(40), 7 custcontactno varchar(20) 8 ); 9 insert into customer values('c001','Shayam kumar','delhi','7777');

Here is Java Source code

001 import java.sql.*; 002 import java.io.*; 003 004 public class StatementDemo1 { 005 006 Connection con; 007 Statement stmt; 008 009 public StatementDemo1() { 010 try { 011 Class.forName("com.mysql.jdbc.Driver"); 012 con = DriverManager.getConnection("jdbc:mysql://localhost/test?user=root&password=root"); 013 } catch (Exception e) { 014 e.printStackTrace(); 015 } 016 } 017 018 public String addCustomer(String custId, String name, String address, String contact) { 019 String status = "", sql = "insert into Customer(custId,custName) values('" + custId + "','" + name + "')"; 020 if (address.trim().length() != 0) { 021 sql = "insert into Customer(custId,custName,custAddress) values('" + custId + "','" + name + "','" + a 022 } 023 if (contact.trim().length() != 0) { 024 sql = "insert into Customer(custId,custName,custAddress,custContact) values('" + custId + "','" + na 025 } 026 try { 027 stmt = con.createStatement(); 028 int i = stmt.executeUpdate(sql); 029 if (i != 0) { 030 status = "Inserted"; 031 } else { 032 status = "Not Inserted"; 033 } 034 035 } catch (Exception e) { 036 e.printStackTrace(); 037 } 038 return status; 039 } 040 041 public String editCustomer(String custid, String address, String contact) { 042 String status = "", sql = ""; 043 if (address.trim().length() != 0) { 044 sql = "update Customer set custAddress='" + address + "' where custId='" + custid + "'"; 045 } 046 if (contact.trim().length() != 0) {

047 048 049 050 051 052 053 054 055 056 057 058 059 060 061 062 063 064 065 066 067 068 069 070 071 072 073 074 075 076 077 078 079 080 081 082 083 084 085 086 087 088 089 090 091 092 093 094 095 096 097 098

sql = "update Customer set custcontact='" + contact + "' where custId='" + custid + "'";

} if ((contact.trim().length() != 0) && (address.trim().length() != 0)) { sql = "update Customer set custAddress='" + address + "',custcontact='" + contact + "' where custId= } if (sql.trim().length() == 0) { status = "Please provide new values"; } else { try { stmt = con.createStatement(); int i = stmt.executeUpdate(sql); if (i != 0) { status = "Customer details updated successfully"; } else { status = "Customer details not updated "; } } catch (Exception e) { e.printStackTrace(); } } return status; } public void searchCustomer(String custid) { String sql = ""; if (custid.trim().length() == 0) { sql = "select * from Customer"; } else { sql = "select * from Customer where custid='" + custid + "'"; } try { stmt = con.createStatement(); ResultSet res = stmt.executeQuery(sql); while (res.next()) { System.out.print(res.getString(1)); System.out.print("\t" + res.getString(2)); System.out.print("\t" + res.getString(3)); System.out.println("\t" + res.getString(4)); } } catch (SQLException e) { e.printStackTrace(); } } public String deleteCustomer(String custId) { String status = ""; String sql = "delete from Customer where custid='" + custId + "'"; try { stmt = con.createStatement(); int i = stmt.executeUpdate(sql); if (i != 0) { status = "Customer details deleted";

099 } else { 100 status = "Customer details not deleted"; 101 } 102 } catch (Exception e) { 103 e.printStackTrace(); 104 } 105 return status; 106 } 107 108 public void menuDisplay() { String custId = "", custName = "", custAddress = "", custContact = ""; 110 try { 111 BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 112 int ch = 0; 113 while (true) { 114 System.out.println("========== Customer Management System ================ \n" 115 + "1. Add Customer \n " 116 + "2. Edit Customer details \n " 117 + "3. Delete Customer \n " 118 + "4. Display Customer's record \n " 119 + "5. Exit \n" 120 + "Enter Choice \n"); 121 String str1 = br.readLine().toString(); 122 ch = Integer.parseInt(str1); 123 switch (ch) { 124 case 1: { 125 // Customer Id can be left blank 126 do { 127 System.out.println("Enter Customer Id [ It can not be left blank ]"); 128 custId = br.readLine(); 129 } while (custId.trim().length() == 0); 130 131 // Customer name can be left blank 132 do { 133 System.out.println("Enter Customer Name"); 134 custName = br.readLine(); 135 } while (custName.trim().length() == 0); 136 137 System.out.println("Enter Customer Address [ If address is not available PRESS Enter ]"); 138 custAddress = br.readLine(); 139 System.out.println("Enter Customer Contact No. [ If Contact No. is not available PRESS En 140 custContact = br.readLine(); 141 System.out.println(addCustomer(custId, custName, custAddress, custContact)); 142 143 break; 144 } 145 case 2: { 146 System.out.println("Customer address and contact no. can be change based on id"); 147 do { 148 System.out.println("Enter Customer Id [ It can not be left blank ]"); 149 custId = br.readLine(); 150 } while (custId.trim().length() == 0);

151 152 System.out.println("Enter New Address [ If address is not available PRESS Enter ]"); 153 custAddress = br.readLine(); 154 System.out.println("Enter New Contact No. [ If Contact No. is not available PRESS Enter ]" 155 custContact = br.readLine(); 156 System.out.println(editCustomer(custId, custAddress, custContact)); 157 break; 158 } 159 case 3: { 160 do { 161 System.out.println("Enter Customer Id to delete [ It can not be left blank ]"); 162 custId = br.readLine(); 163 } while (custId.trim().length() == 0); 164 System.out.println(deleteCustomer(custId)); 165 break; 166 } 167 case 4: { 168 System.out.println("Enter Customer Id [ If you want to display whole record PRESS Enter]" 169 custId = br.readLine(); 170 searchCustomer(custId); 171 break; 172 } 173 case 5: { 174 System.exit(0); 175 } 176 default: 177 break; 178 } 179 } 180 } catch (Exception e) { 181 e.printStackTrace(); 182 } 183 } 184 185 public static void main(String[] args) { 186 StatementDemo1 obj = new StatementDemo1(); 187 obj.menuDisplay(); 188 } 189 } Working with PreparedStatement interface The java.sql.PreparedStatement interface object represents a precompiled SQL statement. This object is used to efficiently execute SQL statements multiple times. We want to insert a record in a table by putting different values every time. It increase the performance of source code and save time also. It is derived from java.sql.Statement interface. To use PreparedStatement interface in source code, first we need to create object of PreparedStatement by calling prepareStatement() method. The prepareStatement() is available in java.sql.Connection interface.

The prepareStatement() method takes SQL statement in java format. Syntax : prepareStatement("insert into emp values(?,?,?,?)"). The each ? represent the column index number in the table. If table EMP has code, name, city and salary columns, then 1st ? refer to code, 2nd ? refer to name, 3rd ? refer to city and 4th ? refer to salary. You can insert partial record in the table. Syntax : prepareStatement("insert into emp(code,name,salary) values(?,?,?)"). Here 1st ? refer to code,2nd ? refer to name, 3rd ? refer to salary. So ? represent the columns in java SQL statement. If column/s name is not specified with table name, it means we will use whole columns of the table and ? (question mark) index dependes on column index of table. Afterthat we need to set the value to each ? by using the setter method from PreparedStatement interface as follows : Syntax : setXXX(ColumnIndex,value) The following table describe the SQL data type and respective setter methods SQL datatype char/varchar/varchar2 int/number float/number double/Float long/int int/short time datetime/date blob Method used setString() setInt() setFloat() setDouble() setLong() setShort() setTime() setDate() setBlob()

Insert, Update , Delete & Query a record using PreparedStatement interface . Create a table customer in MySQL database server as follows Table - Customer Column Name Data type custId custname custaddress custcontactno Firstly establish connection with database SQL Syntax for creating table varchar(10) PK varchar(40) varchar(40) varchar(20) [ Type2 driver ]

[ Type1 driver ]

1 use test; 2 create table customer 3( 4 custId varchar(10) primary key, 5 custname varchar(40), 6 custaddress varchar(40), 7 custcontactno varchar(20) 8 ); 9 insert into customer values('c001','Shayam kumar','delhi','7777'); Java Source Code 001 002 import java.sql.*; 003 import java.io.*; 004 005 public class PreparedStatementDemo1 { 006 007 Connection con; 008 PreparedStatement ps; 009 010 public PreparedStatementDemo1() { 011 try { 012 Class.forName("com.mysql.jdbc.Driver"); 013 con = DriverManager.getConnection("jdbc:mysql://localhost/test?user=root&password=root"); 014 } catch (Exception e) { 015 e.printStackTrace(); 016 } 017 } 018 019 public String addCustomer(String custid, String name, String address, String contact) { 020 String status = ""; 021 try { 022 ps = con.prepareStatement("insert into Customer values(?,?,?,?)"); 023 ps.setString(1, custid); 024 ps.setString(2, name); 025 ps.setString(3, address); 026 ps.setString(4, contact); 027 int i = ps.executeUpdate(); 028 if (i != 0) { 029 status = "Inserted"; 030 } else { 031 status = "Not Inserted"; 032 } 033 034 } catch (Exception e) { 035 e.printStackTrace(); 036 } 037 return status; 038 } 039

040 041 042 043 044 045 046 047 048 049 050 051 052 053 054 055 056 057 058 059 060 061 062 063 064 065 066 067 068 069 070 071 072 073 074 075 076 077 078 079 080 081 082 083 084 085 086 087 088 089 090 091

public String editCustomer(String custid, String address, String contact) { String status = ""; try { ps = con.prepareStatement("update Customer set custaddress=?,custcontactno=? where custid=?"); ps.setString(1, address); ps.setString(2, contact); ps.setString(3, custid); int i = ps.executeUpdate(); if (i != 0) { status = "Customer details updated successfully"; } else { status = "Customer details not updated "; } } catch (Exception e) { e.printStackTrace(); } return status; } public void searchCustomer(String custid) { String sql = ""; if (custid.trim().length() == 0) { sql = "select * from Customer"; } else { sql = "select * from Customer where custid='" + custid + "'"; } try { ps = con.prepareStatement(sql); ResultSet res = ps.executeQuery(); while (res.next()) { System.out.print(res.getString(1)); System.out.print(res.getString(2)); System.out.print(res.getString(3)); System.out.println(res.getString(4)); } } catch (SQLException e) { e.printStackTrace(); } } public String deleteCustomer(String custId) { String status = ""; try { ps = con.prepareStatement("delete from Customer where custid=?"); ps.setString(1, custId); int i = ps.executeUpdate(); if (i != 0) { status = "Customer details deleted"; } else { status = "Customer details not deleted"; } } catch (Exception e) {

092 093 094 095 096 097 098 099 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143

e.printStackTrace(); } return status; } public void menuDisplay() { try { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); int ch = 0; while (true) { System.out.println("========== Customer Management System ================ \n" + "1. Add Customer \n " + "2. Edit Customer details \n " + "3. Delete Customer \n " + "4. Display Customer's record \n " + "5. Exit \n" + "Enter Choice \n"); String str1 = br.readLine().toString(); ch = Integer.parseInt(str1); switch (ch) { case 1: { System.out.println("Enter Customer Id"); String custId = br.readLine(); System.out.println("Enter Customer Name"); String custName = br.readLine(); System.out.println("Enter Customer Address"); String custAddress = br.readLine(); System.out.println("Enter Customer Contact No."); String custContact = br.readLine(); System.out.println(addCustomer(custId, custName, custAddress, custContact)); break; } case 2: { System.out.println("Customer address and contact no can be change based on id"); System.out.println("Enter Customer Id"); String custId = br.readLine(); System.out.println("Enter New Address"); String custAddress = br.readLine(); System.out.println("Enter New Contact No."); String custContact = br.readLine(); System.out.println(editCustomer(custId, custAddress, custContact)); break; } case 3: { System.out.println("Enter Customer Id to delete from database"); String custId = br.readLine(); System.out.println(deleteCustomer(custId)); break; } case 4: { System.out.println("Enter Customer Code to display record");

144 String custId = br.readLine(); 145 searchCustomer(custId); 146 break; 147 } 148 case 5: { 149 System.exit(0); 150 } 151 default: 152 break; 153 } 154 } 155 } catch (Exception e) { 156 e.printStackTrace(); 157 } 158 } 159 160 public static void main(String[] args) { 161 PreparedStatementDemo1 obj = new PreparedStatementDemo1(); 162 obj.menuDisplay(); 163 } 164 } Working with CallableStatement interface A java.sql.CallableStatement interface object is used to call stored procedures from the database. It is the standard way to execute stored procedure for all DBMS/RDBMS. A stored procedure is an object stored in a database. The database stored procedure can be in following form : Without parameter With input parameter With output parameter With input and output parameter Both input and output may have a variable number of parameters used for input (IN parameters), output (OUT parameters), or both (INOUT parameters). A question mark serves as a placeholder for a parameter. Syntax : Without parameter - {call procedure_name} With input parameter - {call procedure_name[(?, ?, ...)]} Stored procedure that returns value - {? = call procedure_name[(?, ?, ...)]} It is derived from java.sql.PreparedStatement interface. So we can use all the methods from Statement and PreparedStatement interface type for setting and getting value. First establish connection with database [ Type1 driver ] [ Type2 driver ]

Table structure in MySQL as follows : 1 use test; 2 create table Emp 3( 4 code varchar(10) primary key, 5 name varchar(40) null, 6 city varchar(20), 7 salary int 8 ); 9 insert into Emp values('a001','Ram Kumar','Noida',10000);

Here creating different type of Stored Procedure in MySQL database server and call in Java source code Stored Procedure without parameter We create a stored procedure without parameter in MySQL database server. I create proc1 procedure, it shows average salary of employee from EMP table SQL statement for stored procedure 1 DELIMITER // 2 3 CREATE PROCEDURE proc1() 4 BEGIN 5 SELECT Avg(salary) AS salary 6 FROM emp; 7 END; // 8 9 DELIMITER ;

Here is the Java source code to call stored procedure proc1 from database 01 // This method use proc1 procedure 02 // proc1 display average salary of employee from EMP table 03 public void callProcedure1() { 04 try { 05 clmt = con.prepareCall("{call proc1}"); 06 ResultSet res = clmt.executeQuery(); 07 if (res.next()) { 08 System.out.println(res.getString(1)); 09 } 10 } catch (Exception e) { 11 e.printStackTrace(); 12 } 13 }

Stored procedure that return records from table We create a stored procedure without parameter in MySQL database server. I create proc2 procedure, it shows whole employee records from EMP table SQL statement for stored procedure 1 DELIMITER // 2 3 CREATE PROCEDURE proc2() 4 BEGIN 5 SELECT * FROM emp; 6 END; // 7 8 DELIMITER ;

Here is the Java source code to call stored procedure proc2 from database 01 // This method use proc2 procedure 02 // It displays the whole records from Emp table 03 public void callProcedure2() { 04 try { 05 clmt = con.prepareCall("{call proc2}"); 06 ResultSet res = clmt.executeQuery(); 07 while (res.next()) { 08 System.out.println(res.getString(1) + "\t" + res.getString(2) 09 + "\t" + res.getString(3) + "\t" + res.getString(4)); 10 } 11 } catch (Exception e) { 12 e.printStackTrace(); 13 } 14 } Stored procedure with two IN parameter We create a stored procedure with parameter in MySQL database server. I create a procedure proc3, it takes two input parameters as an employee code and employee name and store it in Emp table SQL statement for stored procedure 1 DELIMITER // 2 3 CREATE PROCEDURE proc3(IN code1 varchar(10),IN name1 varchar(10)) 4 BEGIN 5 insert into emp(code,name) values(code1,name1); 6 END; //

7 8 DELIMITER ;

Here is the Java source code to call stored procedure proc3 from database 01 // call procedure proc3 with two IN parameters and store in emp table 02 public void callProcedure3(String code, String name) { 03 try { 04 clmt = con.prepareCall("{call proc3(?,?)}"); 05 clmt.setString(1, code); 06 clmt.setString(2, name); 07 int i = clmt.executeUpdate(); 08 if (i != 0) 09 System.out.println("Inserted successfully"); 10 else 11 System.out.println("Not Inserted"); 12 } catch (Exception e) { 13 } 14 } Stored procedure with one IN and OUT parameter We create a stored procedure with parameter in MySQL database server. I create proc4 procedure, it takes an input parameter as employee code and return employee name as an OUTPUT parameter from EMP table SQL statement for stored procedure 1 DELIMITER // 2 3 CREATE PROCEDURE proc4(IN code1 varchar(10),OUT name1 varchar(10)) 4 BEGIN 5 SELECT name from emp where code=code1 6 INTO name1; 7 END; // 8 9 DELIMITER ;

Here is the Java source code to call stored procedure proc4 from database 01 // procedure with one in and one out parameter 02 // It takes emp code as parameter and return emp name as output parameter 03 public void callProcedure4(String code) { 04 try { 05 clmt = con.prepareCall("{call proc4(?,?)}");

06 clmt.setString(1, code); 07 clmt.registerOutParameter(2, Types.VARCHAR); 08 clmt.execute(); 09 System.out.println(clmt.getString(2)); 10 } catch (Exception e) { 11 } 12 } Stored procedure with INOUT parameter We create a stored procedure with parameter in MySQL database server. I create proc5 procedure, it takes an input parameter as employee code and return employee name as an OUTPUT parameter using INOUT parameter from EMP table SQL statement for stored procedure 1 DELIMITER // 2 3 CREATE PROCEDURE proc5(INOUT var1 varchar(20)) 4 BEGIN 5 SELECT name from emp where code=var1 6 INTO var1; 7 END; // 8 9 DELIMITER ;

Here is the Java source code to call stored procedure proc5 from database 01 // proc5 procedure takes one IN parameter and return value in OUT parameter 02 // It uses single INOUT parameter for both purpose 03 public void callProcedure5(String var1) { 04 try { 05 clmt = con.prepareCall("{call proc5(?)}"); 06 clmt.registerOutParameter(1, Types.VARCHAR); 07 clmt.setString(1, var1); 08 clmt.execute(); 09 System.out.println(clmt.getString(1)); 10 } catch (Exception e) { 11 } 12 }

JDBC ResultSet interface JDBC ResultSet is an interface of java.sql package. It is a table of data representing a database query result, which is obtained by executing the execute method of statement. A ResultSet object points the cursor to the first row of the data. Initially the cursor point before the fist row of the data. to move the cursor next() method is called. If there is no any row present in the result then it returns the false value. The default ResultSet object is not updateable therefore the cursor moves only forward from the first row to the last row only once. It is possible to make ResultSet object that is updateable and acrollable. to

The following methods are used to navigate the ResultSet obejct Navigation methods boolean next() boolean previous() boolean first() boolean last() boolean relative(int rows) boolean absolute(int row) void afterLast() void beforeFirst() Description Moves the cursor to next record from its current position. Moves the cursor to the previous record from its current position. Moves the cursor to the first row in this ResultSet object. Moves the cursor to the last row in this ResultSet object. Moves the cursor a relative number of rows, either positive or negative. Moves the cursor to the given row number in this ResultSet object. Moves the cursor to the end of this ResultSet object, just after the last row.

Moves the cursor to the front of this ResultSet object, just before the first row. Statement stmt = con.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); ResultSet rs = stmt.executeQuery("SELECT * FROM Student"); The ResultSet object also provides a getter method that that gets the value from the ResultSet object table. You need to specify only the Column name or index no of the table. For exampleresultSet.getString("ColumnName");, resultSet.getInt("ColumnName");, You can update the database table from the resultSet object as Statement statement = connection.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); resultSet.first(); // Setting the updating String

resultSet.updateString("Name", "vnay"); // Updating the first row resultSet.updateRow(); An Example given below illustrate the above explanations, At first create database named student and then create a table student in the student database as CREATE TABLE student ( RollNo int(9) PRIMARY KEY NOT NULL, Name tinytext NOT NULL, Course varchar(25) NOT NULL, Address text ); Then insert the value into it as NSERT INTO student VALUES(1, 'Ram', 'B.Tech', 'Delhi') ; NSERT INTO student VALUES(2, 'Syam', 'M.Tech', 'Mumbai') ;

JDBCResultSetExample.java package roseindia.net; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class JDBCResultSetExample { Connection connection = null; public JDBCResultSetExample() { try { // Loading the driver Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { System.out.println(e.toString()); } } public Connection createConnection() { Connection con = null; if (connection != null) { System.out.println("Cant create a connection"); } else { try { // Crating a Connection to the Student database con = DriverManager.getConnection( "jdbc:mysql://localhost:3306/student", "root", "root"); System.out.println("Connection created Successfully"); } catch (SQLException e) { System.out.println(e.toString()); }

} return con; } public static void main(String[] args) throws SQLException { JDBCResultSetExample resultSetExample = new JDBCResultSetExample(); Connection connection = resultSetExample.createConnection(); try { // creating a statement object Statement statement = connection.createStatement( ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE); String query = "SELECT * FROM student"; // executing a query string and storing it into the resultSet object ResultSet resultSet = statement.executeQuery(query); System.out.println("Before Updating....................\n"); while (resultSet.next()) { // Printing results to the console System.out.println("Roll No- " + resultSet.getInt("RollNo") + ", Name- " + resultSet.getString("Name") + ", Course- " + resultSet.getString("Course") + ", Address- " + resultSet.getString("Address")); } // setting the row to we have to update resultSet.first(); // Setting the updating String resultSet.updateString("Name", "vnay"); // Updating the first row resultSet.updateRow(); System.out.println("\n\n After Updatig.......................\n"); while (resultSet.next()) { // Printing results to the console System.out.println("Roll No- " + resultSet.getInt("RollNo") + ", Name- " + resultSet.getString("Name") + ", Course- " + resultSet.getString("Course") + ", Address- " + resultSet.getString("Address")); } } catch (Exception e) { System.out.println(e.toString()); } finally { connection.close(); } }

JDBC ResultSetMetaData The simple meaning of metadata is data about data. There are two metadata available in the JDBC API - ResultSetMetaData and DatabaseMetaData. ResultSetMetaData ResultSetMetaData is used to make descriptive information about ResultSet object, like; number of

columns, name of columns and dataype of columns. It does not provide any information regarding database and how many rows are available in the ResultSet object. Whether ResultSet is read only, updatable or scrollable. First we have to create object of ResultSetMetadata by calling getMetaData() method from ResultSet object. Syntax : ResultSetMetaData rsmd=res.getMeataData(); // res is a valid object of ResultSet object The following are common methods in ResultSetMetadata interface int getColumnCount() String getColumnName() int getColumnType() String getTableName() The following is the source code to demostrates ResultSetMetaData interface. Here user will input table name and display the result with column heading01 import java.sql.*; 02 import java.io.*; 03 public class ResultSetMetaDataDemo1 04 { 05 Connection con; 06 public ResultSetMetaDataDemo1() 07 { 08 try 09 { 10 Class.forName("com.mysql.jdbc.Driver"); 11 con = DriverManager.getConnection("jdbc:mysql://localhost/test?user=root&password=root"); 12 } 13 catch (Exception e) 14 { 15 System.out.println("Error in connection" + e); 16 } 17 } 18 public void displyRecords(String tableName) 19 { 20 String columnHeading=""; 21 try 22 { 23 Statement stmt=con.createStatement(); 24 ResultSet res=stmt.executeQuery("select * from "+tableName.trim()); 25 if(res.next()) 26 { 27 ResultSetMetaData rsmd=res.getMetaData(); 28 int columnCount=rsmd.getColumnCount(); 29 for (int i = 1; i<= columnCount; i++) { 30 columnHeading=columnHeading+"\t"+rsmd.getColumnName(i); 31 }

32 System.out.println(columnHeading); 33 34 while(res.next()) 35 { 36 for (int i = 1; i<= columnCount; i++) 37 { 38 System.out.print("\t"+res.getString(i)); 39 40 } 41 System.out.println("\n"); 42 43 } 44 } 45 else 46 System.out.println("There is no records in table"); 47 } 48 catch (Exception e) 49 { 50 e.printStackTrace(); 51 } 52 } 53 public static void main(String[] args) 54 { 55 ResultSetMetaDataDemo1 obj=new ResultSetMetaDataDemo1(); 56 BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); 57 String choice=""; 58 try 59 { 60 do{ 61 System.out.println("Enter table name to display records using ResultSetMeataData interface"); 62 String name=br.readLine(); 63 obj.displyRecords(name); 64 System.out.println("Do you wanto to continue(yes)"); 65 choice=br.readLine(); 66 }while(choice.trim().equals("yes")); 67 68 } 69 catch(Exception e) 70 { 71 e.printStackTrace(); 72 } 73 } 74 }

JDBC Database Meta Data The java.sql.DatabaseMetaData interface provide comprehensive information about the database. It contains the information about Database Management System (DBMS) and all the objects in the database, like; all the tables, cataloge name, view, stored procedure etc.

First we need to create DatabaseMetaData object by calling getMetaData() from Connection interface. It provide whole information about database so getMetaData() method is available in the Connection interface. Syntax: DatabaseMetaData dmd=con.getMetaData(); // con is an object of Connection interface The following are common methods available in DatabaseMetaData interface: ResultSet getCatalogs() int getDatabaseMajorVersion() int getDatabaseMinorVersion() String getDatabaseProductName() String getDatabaseProductVersion() int getDefaultTransactionIsolation() int getDriverMajorVersion() int getDriverMinorVersion() String getDriverName() String getDriverVersion() The following source code to demostrates the DatabaseMetaData interface. It takes database name from user and display all the tables from the database. 01 import java.sql.*; 02 import java.util.Vector; 03 04 public class DatabaseMetadataDemo1 { 05 Connection con; 06 07 public DatabaseMetadataDemo1() { 08 try { 09 Class.forName("com.mysql.jdbc.Driver"); 10 con = DriverManager 11 .getConnection("jdbc:mysql://localhost/test?user=root&password=root"); 12 } catch (Exception e) { 13 System.out.println("Error in connection" + e); 14 } 15 } 16 17 public void useMetaData() { 18 try { 19 // to obtain DatabaseMetadata object 20 DatabaseMetaData dm = con.getMetaData(); 21 System.out.println("Get database Major Version : - "+ dm.getDatabaseMajorVersion()); 22 System.out.println("Get database Minor Version : - "+ dm.getDatabaseMinorVersion()); 23 System.out.println("get Database Product name : - " + dm.getDatabaseProductName()); 24 System.out.println("get Database Product Version : - "+ dm.getDatabaseProductVersion()); 25 System.out.println("Get JDBC Driver Major Version :- "+ dm.getDriverMajorVersion());

26 System.out.println("Get JDBC Driver Minor Version :- "+ dm.getDriverMinorVersion()); 27 System.out.println("Get driver Name : -" + dm.getDriverName()); 28 System.out.println("get driver version :- " + dm.getDriverVersion()); 29 System.out.println("Get JDBC Major version :- "+ dm.getJDBCMajorVersion()); 30 System.out.println("Get JDBC Minor version :- "+ dm.getJDBCMinorVersion()); 31 System.out.println("==========="); 32 String[] types = { "TABLE" }; 33 String catalog = con.getCatalog(); 34 String schema = "test"; // name of the database 35 DatabaseMetaData dmd = con.getMetaData(); 36 ResultSet rset = dmd.getTables(catalog, schema, null, types); 37 while (rset.next()) { 38 System.out.println(rset.getString(3)); 39 } 40 } catch (Exception e) { 41 e.printStackTrace(); 42 } 43 } 44 45 public static void main(String[] args) { 46 DatabaseMetadataDemo1 obj = new DatabaseMetadataDemo1(); 47 obj.useMetaData(); 48 } 49 } Download

JDBC-BATCH "A batch is a group of one or more SQL (Structured Query Language) statements sent in one go to the SQL Server from an application for execution. The SQL Server parse the SQL statements in a single executable unit, called an SQL statement statement execution plan. The statements in the execution plan are then executed by the server in one go." In Java, JDBC support batch processing using java.sql.Statement and java.sql.PreparesStatement inrerfaces. We can submit multiple DML(Data Manupulation Language) statements to the database server in one call from java application using java.sql package. Only insert, update and delete statements are allowed in batch processing in java. It minimize the number of hits (calls) to database server from java applications. We can create batch by calling addBatch("Insert or Update or Delete sql statement") method from Statement or PreparesStatement interface. After adding all the statements, call executeBatch() to execute batch. The return type is arry type of int. The values in the itn array indicates how many are affected by the SQL statement in database server. Syntax : SQL statements to batch stmt.addBatch("insert into emp values('a001','ram','noida',1000)"); stmt.addBatch("insert into emp values('a002','shayam','pune',2000)"); stmt.addBatch("insert into emp values('a003','raman','kolkata',3000)");

stmt.addBatch("insert into emp values('a004','suman','mumbai',4000)"); Execute batch in database server int i[] = st.executeBatch(); Follwoing is the source code to demostrates the batch processing using JDBC Here I am inserting multiple records in Student table using batch -

01 package jdbc; 02 03 import java.sql.Connection; 04 import java.sql.DriverManager; 05 import java.sql.ResultSet; 06 import java.sql.Statement; 07 08 public class BatchDemo1 { 09 Connection con; 10 Statement stmt; 11 12 public BatchDemo1() { 13 try { 14 Class.forName("com.mysql.jdbc.Driver"); 15 con = DriverManager 16 .getConnection("jdbc:mysql://localhost/test?user=root&password=root"); 17 } catch (Exception e) { 18 System.out.println("Error in connection" + e); 19 } 20 } 21 22 // Create table in database server 23 public void createTable() { 24 try { 25 String sql1 = "drop table if exists Student"; 26 String sql = "create table Student(rollNo int primary key, Name varchar(30), Dob varchar(20), Course va 27 28 // drop the table if exists 29 stmt = con.createStatement(); 30 stmt.executeUpdate(sql1); 31 32 // execute SQl statement to execute create table statement 33 stmt = con.createStatement(); 34 int i = stmt.executeUpdate(sql); 35 System.out.println("Table created"); 36 } catch (Exception e) { 37 e.printStackTrace(); 38 } 39 } 40 41 public void batchProcess() { 42 try { 43 stmt.addBatch("insert into Student values(1,'Ram Kumar','10-02-1990','BTech')"); 44 stmt.addBatch("insert into Student values(2,'Shayam Kumar','15-05-1992','BTech')");

45 stmt.addBatch("insert into Student values(3,'Ritu Kumari','4-07-1989','MCA')"); 46 stmt.addBatch("insert into Student values(4,'Suman Saurabh','12-12-1995','MCA')"); 47 stmt.addBatch("insert into Student values(5,'Suresh Sharma','10-11-1991','BTech')"); 48 int i[] = stmt.executeBatch(); 49 for (int j : i) { 50 if (j != 0) 51 System.out.println("Executed successfully"); 52 else 53 System.out.println("Not Executed successfully"); 54 } 55 } catch (Exception e) { 56 e.printStackTrace(); 57 } 58 } 59 60 public void showRecords() { 61 try { 62 stmt = con.createStatement(); 63 ResultSet res = stmt.executeQuery("select * from Student"); 64 while (res.next()) { 65 System.out.print(res.getString(1)); 66 System.out.print("\t" + res.getString(2)); 67 System.out.print("\t" + res.getString(3)); 68 System.out.println("\t" + res.getString(4)); 69 } 70 71 } catch (Exception e) { 72 System.out.println("Error in fetching data" + e); 73 } 74 } 75 76 public static void main(String[] args) { 77 BatchDemo1 obj = new BatchDemo1(); 78 obj.createTable(); 79 obj.batchProcess(); 80 obj.showRecords(); 81 } 82 } "A transaction is a logical group of work that contains one or more SQL statements. Either all, or none of the statements need to be performed in order to preserve data integrity" A complete task which is a combination of the multiple smaller tasks. For a major task to be completed, smaller tasks need to be successfully completed. If any one task fails then all the previous tasks are reverted back to the original state, means that database server guarantee to follow the ACID (Automicity, Consistency, Isolation and Durability) properties. A transaction is an atomic unit. ACID Properties Atomicity : Implies indivisibility

Any indivisible operation (one which will either complete in totally, or not at all) is said to be atomic Consistency : A transaction must transition persistent data from one consistent state to another In the event of a failure occurs during processing, data must be restored to the state it was in prior to the transaction Isolation : Transactions should not affect each other A transaction in progress, not yet committed or rolled back, must be isolated from other transactions Durability : Once a transaction commits successfully, the state changes committed by that transaction must be durable < persistent, despite any failures that occur afterwards JDBC Transaction Management : The Connection interface is used to manage transactions in Java applications. There is three methods setAutoCommit(), commit() and rollback() used to implement transaction in JDBC. By default true is set in setAutoCommit() method, when any SQL statement submit to the database server, database server commit it. We can set false in setAutoCommit() method to commit or rollback transaction either commit or rollback explicitly respectively by calling commit(0 and rollback() method. Example - I am using Account table. The amount must be available at least Rs.- 1000.00. After withdrawing amount from account, it will check the amount in account, If it is less than 1000 the transaction must be rollback.

Create table in database server 01 use test; 02 drop table if exists Account; 03 create table Account 04 ( 05 accId varchar(10) primary key, 06 accName varchar(40), 07 accType varchar(10), 08 amount double 09 ); 10 insert into Account values('a001','Ram kumar','Saving',5000.50); 11 insert into Account values('a002','Shayam kumar','Saving',5600.50); 12 insert into Account values('a003','MOhan kumar','Saving',4060.50); 13 insert into Account values('a004','Ravi Singh','Saving',9000.50); 14 insert into Account values('a005','Suraj Suman','Saving',85000.50); Download Following source code to demostrates the JDBC transaction -

01 package jdbc; 02 03 import java.sql.*; 04 import java.io.*; 05 06 public class JDBCTransactionDemo1 07 { 08 Connection con; 09 PreparedStatement ps, ps1; 10 BufferedReader br; 11 12 public JDBCTransactionDemo1() { 13 try 14 { 15 Class.forName("com.mysql.jdbc.Driver"); 16 con = DriverManager.getConnection("jdbc:mysql://localhost/test?user=root&password=root"); 17 br = new BufferedReader(new InputStreamReader(System.in)); 18 } 19 catch (Exception e) 20 { 21 System.out.println("Error in connection" + e); 22 } 23 } 24 25 public void withdrawalAmt() 26 { 27 try 28 { 29 System.out.println("Enter account no"); 30 String accid = br.readLine().trim(); 31 System.out.println("Enter Amount to withdrawal"); 32 double amt = Double.parseDouble(br.readLine().trim()); 33 con.setAutoCommit(false); 34 ps = con.prepareStatement("update Account set amount=amount-? where accId=?"); 35 ps.setDouble(1, amt); 36 ps.setString(2, accid); 37 ps.executeUpdate(); 38 ps = con.prepareStatement("select amount from Account where accId=?"); 39 ps.setString(1, accid); 40 ResultSet res = ps.executeQuery(); 41 res.next(); 42 double balAmt = res.getDouble(1); 43 System.out.println("The balance amount is " + balAmt); 44 if (balAmt < 1000) 45 { 46 System.out.println("The transaction can not be compltete"); 47 con.rollback(); 48 } 49 else 50 { 51 System.out.println("The transaction complteted successfully"); 52 con.commit();

53 } 54 res.close(); 55 ps.close(); 56 } 57 catch (Exception e) 58 { 59 e.printStackTrace(); 60 } 61 } 62 63 public static void main(String[] args) 64 { 65 new JDBCTransactionDemo1().withdrawalAmt(); 66 } 67 }

Vous aimerez peut-être aussi