Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
30 views

Module4 JDBC PDF

The document discusses JDBC (Java Database Connectivity), which is a standard Java API for connecting to and executing queries with databases. It describes the JDBC architecture as having two layers: the JDBC API and JDBC Driver API. There are four types of JDBC drivers discussed - JDBC-ODBC bridge, native-API, network protocol, and thin driver - along with their advantages and disadvantages. The document also outlines the seven steps to connect a Java application to a database using JDBC: import packages, load driver class, open connection by defining URL and establishing connection, create statement, execute query, process results, and close connection.

Uploaded by

VTU ML Workshop
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

Module4 JDBC PDF

The document discusses JDBC (Java Database Connectivity), which is a standard Java API for connecting to and executing queries with databases. It describes the JDBC architecture as having two layers: the JDBC API and JDBC Driver API. There are four types of JDBC drivers discussed - JDBC-ODBC bridge, native-API, network protocol, and thin driver - along with their advantages and disadvantages. The document also outlines the seven steps to connect a Java application to a database using JDBC: import packages, load driver class, open connection by defining URL and establishing connection, create statement, execute query, process results, and close connection.

Uploaded by

VTU ML Workshop
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Module-4 JDBC

Chapter -1

JDBC
1.1 Introduction (Talking to JDBC):

JDBC stands for Java Database Connectivity, which is


a standard Java API to connect and execute query with
the database.

The JDBC library includes APIs for each of the tasks


associated with database usage:
 Making a connection to a database
 Creating SQL or MySQL statements
 Executing that SQL or MySQL queries in the
database
 Viewing & Modifying the resulting records

1.2 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:
 JDBC API: This provides the application-to-
JDBC Manager connection. It uses a driver
manager and database-specific drivers to provide
transparent connectivity to heterogeneous
databases. JDBC Driver API

 JDBC Driver API: This supports the JDBC


Manager-to-Driver Connection. 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. Figure-1.1: JDBC Architecture Diagram

Type of JDBC Drivers (Immediate Solution):


JDBC Driver is a software component that enables java application to interact with the database. There are 4 types
of JDBC drivers:
1. JDBC-ODBC bridge driver 3. Network Protocol driver (fully java driver)
2. Native-API driver (partially java driver) 4. Thin driver (fully java driver)

1 | 29
Module-4 JDBC
1. JDBC-ODBC bridge driver:
The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-ODBC bridge driver
converts JDBC method calls into the ODBC function calls.
The driver is a platform dependent because it
uses ODBC which is depends on native
libraries of the operating system and also the
driver needs other installation.
Example: ODBC must be installed on the
computer and the database must support
ODBC driver.
Type-1 is the simplest compare to all other
driver but it’s a platform specific i.e. only on
Microsoft platform. The JDBC-ODBC
Bridge is use only when there is no PURE-
JAVA driver available for a particular
database.
Advantages:
 easy to use as compare the all other driver.
 can be easily connected to any database.

Disadvantages:
 Performance degraded because JDBC method call is converted into the ODBC function calls.
 The ODBC driver needs to be installed on the client machine.
 Not suitable for applets because the ODBC driver needs to be installed on the client machine.

2. Native-API driver
The Native API driver uses the client-side libraries of the database. The driver converts JDBC method calls into
native calls of the database API. It is not written entirely in java.
Advantage:
 There is no implantation of JDBC-ODBC
Bridge so it’s faster than a type-1 driver
 Performance upgraded than JDBC-ODBC
bridge driver.
Disadvantage:
 The Native driver needs to be installed on
the each client machine.
 The Vendor client library needs to be
installed on client machine.
 Not all databases have the client side
library.
 This driver supports all JAVA applications
except applets.

2 | 29
Module-4 JDBC
3. Network Protocol Driver:
The Network Protocol driver uses
middleware (application server) that
converts JDBC calls directly or
indirectly into the vendor-specific
database protocol and the same
driver can be used for multiple
databases. It is fully written in java.
Advantage:
 No client side library is required
because the middleware is
database independent and it
communicates with client.
 Type-3 driver can be used in any web application as well as on internet also because there is no any software
require at client side.
 A single driver can handle any database at client side so there is no need a separate driver for each database.
 The middleware server can also provide the typical services such as connections, auditing, load balancing,
logging etc.
Disadvantages:
 Network support is required on client machine.
 Requires database-specific coding to be done in the middle tier, may be increase complexity.
 Maintenance of Network Protocol driver becomes costly because it requires database-specific coding to be
done in the middle tier.

4. Thin driver:
The thin driver converts JDBC calls
directly into the vendor-specific
database protocol and in between do
not need to be converted any other
formatted system so this is the fastest
way to communicate quires with the
DBMS. It is fully written in Java
language.
Advantage:
 It is a 100% pure JAVA Driver
so it’s a platform independence
 No translation or middleware layers are used so consider as a better performance than all other drivers.
 No software is required at client side or server side.
 The all process of the application-to-database connection can manage by JVM so the debugging is also
managed easily.

3 | 29
Module-4 JDBC
Disadvantage:
 Drivers depends on the Database as different database vendors use different network protocols.
 There is a separate driver needed for each database at the client side.

1.3 Steps to Connect to DB in Java:


There are 7 steps to connect any java application with the database in java using JDBC. They are as follows:
i. Import the Package iv. Creating statement
ii. Load the Driver Class v. Execute a query or update
iii. Open a Connection vi. Process the results
a. Define Connection URL
b. Establish the connection vii. Close the Connection

i. Import the package:


To connect any java application with the database, you import the following package: import java.sql.*;

ii. Load the Driver Class:


To load a driver, you specify the classname of the database driver in the Class.forName method. By doing
so, you automatically create a driver instance and register it with the JDBC driver manager.
Syntax:
public static void forName(String className)
throws ClassNotFoundException

Example: Class.forName("com.mysql.jdbc.Driver");
iii. Open a Connection:
To establish the connection with any database follow the below two step:

a. Define Connection URL: In JDBC, a connection URL specifies the server host, port, and database
name with which to establish a connection.
Syntax: Connection object_name; Example: Connection con;

b. Establish the connection: With the connection URL, username, and password, a network
connection to the database can be established. Once the connection is established, database queries can
be performed until the connection is closed.
Syntax: public static Connection getConnection(String url)
throws SQLException
public static Connection getConnection(String url,
String name, String password) throws SQLException

Example: Connection con = DriverManager.getConnection (“url", “username", “password");


Connection con = DriverManager.getConnection ("jdbc:mysql://localhost:3309/mysql", "root",
"rnsit");

4 | 29
Module-4 JDBC
The Connection class instance includes other useful methods to create reference for different statements,
which briefly describe below.
Methods Description
createStatement Create Statement object without any parameter to the database.
prepareStatement Creates precompiled queries for submission to the database.
prepareCall Accesses stored procedures in the database
rollback/commit Controls transaction management.
close Terminates the open connection.
isClosed Determines whether the connection timed out or was explicitly closed.

iv. Create a Statement object:


Creating a Statement object enables you to send queries and commands to the database.
Syntax: public Statement createStatement()throws SQLException
Example: Statement stmt=con.createStatement();
Statement object is created from the Connection using createStatement. The object of statement is
responsible to execute queries with the database.

v. Execute a query or update:


Given a Statement object, you can send SQL statements to the database by using execute, executeQuery,
executeUpdate, or executeBatch methods.
Syntax:
public ResultSet executeQuery(String sql)throws SQLException
Example: ResultSet rs=stmt.executeQuery("select * from student");
The executeQuery() method of Statement interface is used to execute queries to the database. This method
returns the object of ResultSet that can be used to get all the records of a table.

vi. Process the result:


When a database query is executed, a ResultSet is returned. The ResultSet represents a set of rows and
columns that you can process by calls to next and various getXxx methods.

Syntax: ResultSet rs=stmt.executeQuery("select * from student");


while(rs.next()) {
System.out.println(rs.getInt(1)+" "+rs.getString(2));
\
}
vii. Close the connection:
When you are finished performing queries and processing results, you should close the connection, releasing
resources to the database.
Syntax: Example:
public void close() throws SQLException con.close();
The close() method of Connection interface is used to close the connection.
5 | 29
Module-4 JDBC
1.4 Using Statement Interfaces:
Through the Statement object, SQL statements are sent to the database. Three types of statement objects are
available listed below:

Interfaces Description
For executing a simple SQL statement that means the Statement object is used to execute
simple or static queries. It is created using createStatement( ) method in Connection class.
Statement

Syntax: Statement obj_name= con.createStatement();


Example: Statement st=null;
St=con.createStatement( );
Example: Refer Examples-1 to 5
For executing a precompiled SQL statement passing in parameters that means
PreparedStatement object is used to execute query with different parameters. These
parameter must be compiled before execution. It is created using prepareStatement( )
method in Connection class.
PreparedStatement

Syntax: PreparedStatment obj_name=con.prepareStatement();


Example: PreparedStatement pre = con.prepareStatement("insert into studinfo values(?)" );
pre.setString(1,usn);
All parameters in JDBC are represented by the ? symbol, which is known as the parameter
marker. You must supply values for every parameter before executing the SQL statement.
The setXXX( ) methods bind values to the parameters, where XXX represents the Java data
type of the value you wish to bind to the input parameter.
setXXX() method takes two arguments representing position of marker (?) and value to
replace respectively.
Example: Refer Examples-6 to 10
For executing a database stored procedure that means the CallableStatement object which
would be used to execute a call to a database stored procedure. It is created using
CallableStatement

prepareCall( ) method in Connection class.

Syntax: CallableStatement obj_name=con.prepareCall();


Example: CallableStatement cstmt = conn.prepareCall (call {getAllData});
Here, getAllData is a stored procedure defined in database, which contains multiple SQL
queries and gets executed when stored procedure is called.
Example: Refer Examples-13 to 14

6 | 29
Module-4 JDBC
Commonly the following methods are used to execute the statements:
SN Methods Description
is used to execute SELECT query. It returns the object
1 public ResultSet executeQuery(String sql) of ResultSet. The ResultSet may be empty, but never
null.
Example: ResultSet results = statement.executeQuery("SELECT a, b FROM table");
is used to execute specified query, it may be create,
2 public int executeUpdate(String sql) drop, insert, update, delete etc. Returns the number of
rows affected, which could be zero.
Example: int rows = statement.executeUpdate("DELETE FROM table WHERE id=xxx“);
is used to execute queries that may return multiple
3 public boolean execute(String sql) results. Returns a boolean value of true if a ResultSet
object can be retrieved; otherwise, it returns false.
Example: boolean result= statement.execute(“SELECT column_name from table");
is used to executes a group of commands as a unit,
4 public int[] executeBatch() returning an array with the update counts for each
command.

Example-1: To establish the connection to MySQL


MySQlConnection.java
package StatementDemo;
import java.sql.*;
public class MySQlConnection {
public static void main(String args[]){
String username ="root";
String password ="rnsit";
String url ="jdbc:mysql://localhost:3309/employeedb";
String driver= "com.mysql.jdbc.Driver";
Connection con =null;

try{ Class.forName(driver).newInstance();
con=DriverManager.getConnection(url, username, password);
System.out.println("Connection successfully established");
con.close();
System.out.println("Connection terminated !");
}
catch(Exception e){
System.out.println("Connection failed !!"+e);
}
}
}

7 | 29
Module-4 JDBC
Example-2: After establish the connection, INSERT records to the database using executeUpdate method with
the Statement object.
MySQLInsert.java
package StatementDemo;
import java.sql.*;

public class MySQLInsert {


public static void main(String args[]){
String username ="root";
String password ="rnsit";
String url ="jdbc:mysql://localhost:3309/employeedb";
String driver= "com.mysql.jdbc.Driver";

Connection con =null;


try{
Class.forName(driver).newInstance();
con=DriverManager.getConnection(url, username, password);
System.out.println("Connection successfully established");
//Creating Statement to execute insert query
Statement statement = con.createStatement();
String query= "INSERT into empinfo VALUES(105, 'Manas') ";
int rs=statement.executeUpdate(query);
if(rs==1){
System.out.println("Record Inserted");
con.close();
}
else {
System.out.println("Record not inserted");
con.close();
}
System.out.println("Connection terminated !");
}
catch(Exception e){
System.out.println("Connection failed !!"+e);
}
}
}

8 | 29
Module-4 JDBC
Example-3: After established the connection, SELECT records to the database using executeQuery method with
the Statement object.
MySQLSelect.java
package StatementDemo;
import java.sql.*;
public class MySQLSelect {
public static void main(String args[]) throws SQLException{
String url ="jdbc:mysql://localhost:3309/employeedb";
String driver= "com.mysql.jdbc.Driver";
Connection con =null;
try{ Class.forName(driver).newInstance();
con=DriverManager.getConnection(url, "root", "rnsit");
Statement statement = con.createStatement();
String query= "select * from empinfo";
ResultSet res = statement.executeQuery(query);
while(res.next()){
System.out.println("Employee-id :" + res.getString("eid")
+ "Employee Name :" + res.getString("ename"));
}
con.close();
System.out.println("Connection Terminated");
} catch(Exception e){
System.out.println("Connection failed !! "+e);
}
}
}

Example-4: After established the connection, UPDATE records to the database using executeUpdate method with
the Statement object.

MySQLUpdate.java
package StatementDemo;
import java.sql.*;
public class MySQLUpdate {
public static void main(String args[]) throws SQLException {
String url ="jdbc:mysql://localhost:3309/employeedb";
String driver= "com.mysql.jdbc.Driver";
Connection con =null;

9 | 29
Module-4 JDBC

MySQLUpdate.java (Continued)
try{ Class.forName(driver).newInstance();
con=DriverManager.getConnection(url, "root", "rnsit");

Statement statement = con.createStatement();


String query= "update empinfo set ename= ‘Manas Ranjan’ where eid=‘105’ ";
int rs = statement.executeUpdate(query);
if(rs==1){
System.out.println("Row Updated");
con.close();
}
else {
System.out.println("Row not Updated");
}
System.out.println("Connection Terminated");
}
catch(Exception e){
System.out.println("Connection failed !!"+e);
}
}
}

Before update
eid =105 After Updated Record

Example-5: After established the connection, DELETE records to the database using executeUpdate method with
the Statement object

MySQLDelete.java
package StatementDemo;
import java.io.IOException;
import java.sql.*;
import java.util.Scanner;
public class MySQLDelete {
public static void main(String args[])throws IOException {
String username ="root";
String password ="rnsit";
String url ="jdbc:mysql://localhost:3309/employeedb";
String driver= "com.mysql.jdbc.Driver";
Connection con =null;

10 | 29
Module-4 JDBC

MySQLDelete.java(Continued)
try{
Class.forName(driver).newInstance();
con=DriverManager.getConnection(url, username, password);
Scanner sc = new Scanner(System.in);
System.out.println("Please enter employee id to delete: ");
int eid = sc.nextInt();
Statement statement = con.createStatement();
String query= "delete from empinfo where eid="+eid+"";
int rs = statement.executeUpdate(query);
if(rs==1){
System.out.println("Record Deleted");
con.close();
}
else{
System.out.println("no such record");
con.close();
}
System.out.println("Connection Terminated");
}
catch(Exception e){
System.out.println("Connection failed !!"+e);
}
}
}

Before Delete Table is After delete eid=103


table is

Example for PreparedStatement:


The following are the methods used to set the queries parameter in PreparedStatement instance.
Methods Description
public void setInt(int paramIndex, int value) sets the integer value to the given parameter index.
public void setString(int paramIndex, String value) sets the String value to the given parameter index.
public void setFloat(int paramIndex, float value) sets the float value to the given parameter index.
public void setDouble(int paramIndex, double val) sets the double value to the given parameter index.
executes the query. It is used for create, drop, insert,
public int executeUpdate()
update, delete etc.
executes the select query. It returns an instance of
public ResultSet executeQuery()
ResultSet.

11 | 29
Module-4 JDBC
Example-6: To establish the connection to MySQL.

MyConnection.java
package MyDatabase;
import java.sql.*;
public class MyConnection {
public static void main(String args[]){
String username ="root";
String password ="rnsit";
String url ="jdbc:mysql://localhost:3309/studentdb";
String driver= "com.mysql.jdbc.Driver";
Connection con =null;

try{ Class.forName(driver).newInstance();
con=DriverManager.getConnection(url, username, password);
System.out.println("Connection successfully established");
con.close();
System.out.println("Connection terminated !");
}
catch(Exception e){
System.out.println("Connection failed !!"+e);
}
}
}

Example-7: After establish the connection, INSERT records to the database using executeUpdate method with
the PreparedStatement object.

MysqlInsert.java
package myDatabase;
import java.sql.*;
public class MysqlInsert {
public static void main(String args[]){
String url ="jdbc:mysql://localhost:3309/studentdb";
String driver= "com.mysql.jdbc.Driver";
String sname="Anusha", usn="1RN13MCA07", Pass="True";
Connection con =null;
try{ Class.forName(driver).newInstance();
con=DriverManager.getConnection(url, “root”, “rnsit”);
System.out.println("Connection successfully established");

12 | 29
Module-4 JDBC

MysqlInsert.java(Continued)
PreparedStatement pre = con.prepareStatement("insert into
studinfo(usn, sname, pass) values(?,?,?)");
pre.setString(1,usn);
pre.setString(2,sname);
pre.setString(3,Pass);
int rs = pre.executeUpdate();
if(rs==1){
System.out.println("RECORD Inserted");
con.close();
}
else {
System.out.println("Insertion FAILED");
con.close();
}
System.out.println("Connection terminated !");
}
catch(Exception e){
System.out.println("Connection failed !!"+e);
}
}
}
Example-8: After established the connection, SELECT records to the database using executeQuery method with
the PreparedStatement object.

MysqlSelect.java
package MyDatabase;
import java.sql.*;
public class MysqlSelect {
public static void main(String args[]) throws SQLException {
String url ="jdbc:mysql://localhost:3309/studentdb";
try{
Class.forName("com.mysql.jdbc.Driver";).newInstance();
Connection con=DriverManager.getConnection(url,"root","rnsit");
PreparedStatement pre = con.prepareStatement("select * from studinfo");
ResultSet res = pre.executeQuery();
while(res.next()){
System.out.println("Name :" + res.getString("sname")+" USN:"
+ res.getString("usn") +" Result:" + res.getString("pass"));
}
con.close();
}catch(Exception e){
System.out.println(e);
}
}
}

13 | 29
Module-4 JDBC
Example-9: After established the connection, UPDATE records to the database using executeUpdate method with
the PreparedStatement object.

MySqlUpdate.java
package MyDatabase;
import java.sql.*;

public class MySqlUpdate {


public static void main(String args[]) throws SQLException {
String url ="jdbc:mysql://localhost:3309/studentdb";
String driver= "com.mysql.jdbc.Driver";
Connection con =null;
try{ Class.forName(driver).newInstance();
con=DriverManager.getConnection(url, "root", "rnsit");
PreparedStatement pre = con.prepareStatement("update studinfo set
sname='Anusha G' where usn='1rn13mca07' ");
int rs = pre.executeUpdate();
if(rs==1){
System.out.println("Record Updated");
con.close();
}
else {
System.out.println("Record not Updated");
}
}
catch(Exception e){
System.out.println("Connection failed !!"+e);
}
}
}
Before updating the record After updating the record

14 | 29
Module-4 JDBC
Example-10: After established the connection, DELETE records to the database using executeUpdate method
with the PreparedStatement object.

MysqlDelete.java
package MyDatabase;
import java.io.IOException;
import java.sql.*;
import java.util.Scanner;
public class MysqlDelete {
public static void main(String args[])throws IOException {
String url ="jdbc:mysql://localhost:3309/studentdb";
String driver2= "com.mysql.jdbc.Driver";
String usn;
Connection con =null;
try{
Class.forName(driver2).newInstance();
con=DriverManager.getConnection(url, “root”, “rnsit”);
Scanner sc = new Scanner(System.in);
System.out.println("Please enter the usn to delete : ");
usn = sc.next();
PreparedStatement pre = con.prepareStatement("delete from studinfo where usn=?");
pre.setString(1,usn);
int rs = pre.executeUpdate();
if(rs==1){
System.out.println("Record Deleted");
con.close();
}
else{
System.out.println("no such record");
con.close();
}
} catch(Exception e){
System.out.println("Connection failed !!"+e);
}
}
}

15 | 29
Module-4 JDBC
1.5 JDBC in Action ResultSets:
The ResultSet object contains the data returned by the database. executeQuery() method returns the ResultSet
object that contains the data was requested by the query for further processing.
Data in a ResultSet object is logically organized into a virtual table consisting of rows and columns. In addition
to data, it also contains metadata such as column name, column type etc.
The ResultSet uses a virtual cursor to point to a row of a virtual table. The virtual cursor is positioned above the
first row of the data when the ResultSet is returned by the executeQuery( ) method. So virtual cursor must be
moved to first row using next( ) method.
The next( ) method returns a Boolean true if row contains the data, otherwise, a Boolean value false is returned
indicating that no more rows exists in the ResultSet. Once the virtual cursor points to arrow, the getXXX( )
method is used to copy data from the row to variable.

Example: Statement stmt = connection.createStatement();


String selectquery = "select * from user";
ResultSet res = stmt.executeQuery(selectquery);
while(res.next( )) {
System.out.print("User ID :" + res.getInt(1)+ " ");
System.out.println("User Name :" + res.getString(2));
}

Note: A J2EE component must move the virtual cursor to each row and the other methods of ResultSet object to
interact with the data stored in columns in that row.
The following are the ResultSet methods can use to process the result.

Methods Description
next/previous Moves the cursor to the next or previous row in the ResultSet, respectively
The relative method moves the cursor a relative number of rows, either positive (up) or
relative / negative (down).
absolute The absolute method moves the cursor to the given row number. If the absolute value is
negative, the cursor is positioned relative to the end of the ResultSet.
Returns the value from the column specified by the column name or column index as an
getXxx()
Xxx Java Can return 0 or null if the value is an SQL NULL.
Checks whether the last getXxx read was an SQL NULL. This check is important if the
column type is a primitive (int, float etc.) and the value in the database is 0. A zero value
wasNull would be indistinguishable from a database value of NULL, which is returned as a 0. If
the column type is an object (String, Date, etc.), you can simply compare the return value
to null
findColumn Returns the index in the ResultSet corresponding to the specified column name.
getRow Returns the current row number, with the first row starting at 1
Returns a ResultSetMetaData object describing the ResultSet. ResultSetMetaData gives
getMetaData
the number of columns and the column names.
getColumnCount, getColumnName., isReadOnly. getColumnType. isSearchable, isNullable.

16 | 29
Module-4 JDBC

1.6 Batch updates or Batch Processing:


Instead of executing a single query, we can execute a batch (group) of queries. It makes the performance fast. The
java.sql.Statement and java.sql.PreparedStatement interfaces provide methods for batch processing.
Methods of Statement interface used to Method Description
insert more than one record at a time void addBatch(String query) It adds query into batch.
int[] executeBatch() It executes the batch of queries.

Example-11: After established the connection, INSERT more than one records to the database using
executeBatch method with the Statement object.

MySQLInsertB.java //using Statement and executeBatch()


package StatementDemo;
import java.sql.*;
public class MySQLInsertB {
public static void main(String args[]){
String url ="jdbc:mysql://localhost:3309/employeedb";
String driver= "com.mysql.jdbc.Driver";
Connection con =null;
try{
Class.forName(driver).newInstance();
con=DriverManager.getConnection(url, “root”, ”rnsit”);
System.out.println("Connection successfully established");
con.setAutoCommit(false); //Set auto-commit to false
Statement statement = con.createStatement();
statement.addBatch("INSERT into empinfo VALUES(106,'Karthik')");
statement.addBatch("INSERT into empinfo VALUES(107,'Pavan')");
statement.executeBatch();
con.commit();
System.out.println("Record Saved");
con.close();
}
catch(Exception e){
System.out.println("Connection failed !!"+e);
}
}
}

Before inserting After inserted

17 | 29
Module-4 JDBC
Example-12: After established the connection, INSERT more than one records to the database using
executeBatch method with the PreparedStatement object.

MysqlInsertB.java //Using PreparedStatment and executeBatch method


package myDatabase;
import java.sql.*;
public class MysqlInsertB {
public static void main(String args[]){
String url ="jdbc:mysql://localhost:3307/studentdb";
String driver= "com.mysql.jdbc.Driver";
Connection con =null;
try{ Class.forName(driver).newInstance();
con=DriverManager.getConnection(url, “root”, “rnsit”);
System.out.println("Connection successfully established");
PreparedStatement pre = con.prepareStatement("insert into
studinfo(usn,sname,Pass) values(?,?,?)");

con.setAutoCommit(false); //Set auto-commit to false


pre.setString(1,"1rn13mca08");
pre.setString(2,"Apporva G S");
pre.setString(3,"false");
pre.addBatch();
pre.setString(1,"1rn13mca09");
pre.setString(2,"Arun");
pre.setString(3,"true");
pre.addBatch();
pre.executeBatch();
con.commit();
System.out.println("Record Saved");
con.close();
}
catch(Exception e){
System.out.println("Connection failed !!"+e);
}
}
}

Before inserting
After inserted

18 | 29
Module-4 JDBC
1.7 Callable Statement Interface:
To call the stored procedures and functions, CallableStatement interface is used. It also creates the
CallableStatement object, which would be used to execute a call to a database stored procedure.
 Three types of parameters exist: IN, OUT, and INOUT.
 The PreparedStatement object only uses the IN parameter.
 The CallableStatement object can use all the three.
Here are the definition of parameter:
Parameter Description
 A parameter whose value is unknown when the SQL statement is created.
IN
 You bind values to IN parameters with the setXXX() methods.
 A parameter whose value is supplied by the SQL statement it returns.
OUT
 You retrieve values from the OUT parameters with the getXXX() methods.
 A parameter that provides both input and output values.
INOUT  You bind variables with the setXXX() methods and retrieve values with the getXXX()
methods.

If you want to use CallableStatement in java application to interact with databases, then you need to create stored
procedures; to create and call the procedure follow the below steps:
 Creating Stored Procedure:
To create stored procedure for MYSQL as follow below:
Where, procedure_name – Stored
DELIMITER $$
procedure name given by user.
CREATE PROCEDURE procedure_name(Parameters List)
BEGIN Parameters List – need to list each
SQL queries and Statements; parameter and the data type separated by a
END $$ comma

Let us write stored procedure for MySQL, to find a record of CUSTOMER database:-
Example:
DELIMITER $$
CREATE PROCEDURE FindCustomerBYID_SP (IN CustomerID INT)
BEGIN
SELECT * FROM Customer WHERE id=CustomerID;
END $$

 Call Procedures:
To call the stored procedures use keyword “call” and end with semicolon.
Syntax: call procedure_name(parameterlist) ;
Example: call FindCustomerBYID_SP(101) ;
The above example retrieve the data of id=’101’ details from the faculty database by calling procedure
statement FindCustomerBYID_SP by using keyword ‘call’.

19 | 29
Module-4 JDBC
 Once you know about creating stored procedure and calling procedure, now you can call created stored
procedure in java application by creating CallableStatement Object.
When you used CallableStatement object, the prepareCall() method have to use to call stored procedures that
as shown below:
Syntax: public CallableStatement prepareCall("{ call procedurename(?,?. . .?)}");

The prepareCall() method of Connection interface returns the instance of CallableStatement.


Example: CallableStatement stmt=con.prepareCall("{call FindCustomerBYID_SP (?,?)}");
It calls the procedure FindCustomerBYID_SP that receives 2 arguments.
Example-13: After established the connection, SELECT all records from the database using executeQuery
method with the CallableStatement object.

1. Creation of Stored procedure


DELIMITER $$
CREATE PROCEDURE FindCustomerBYID_SP5(OUT CustomerID INT, OUT Cname VARCHAR(25))
BEGIN
SELECT * FROM customer;
END$$

2. Java Program: to retrieve all the customer details from customer table which is in the faculty
database

CallStateDemo.java
package ProcedureStatement;
import java.sql.*;
public class CallStateDemo {
public static void main(String[] args) {
Connection conn = null; CallableStatement stmt = null;
Strin url= "jdbc:mysql://localhost:3309/faculty"
try{ Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to database...");
conn= DriverManager.getConnection( url, "root","rnsit");
//Create a Callable Statement
stmt = conn.prepareCall("{call FindCustomerBYID_SP5(?,?)}");
stmt.registerOutParameter(1, java.sql.Types.INTEGER);
stmt.registerOutParameter(2, java.sql.Types.VARCHAR);
//Execute a stored procedure
ResultSet rs=stmt.executeQuery();

20 | 29
Module-4 JDBC

CallStateDemo.java(Continued)
//Process the result
while(rs.next()){
System.out.println("Customer ID: " + rs.getString("id"));
System.out.println("Customer Name: " + rs.getString("ename"));
}
}
catch(SQLException | ClassNotFoundException se){ }
finally{
System.out.println("Goodbye!");
stmt.close();
conn.close();
}
}
}

Example-14: After established the connection, INSERT records to the database using executeUpdate method
with the CallableStatement object.

1. Creation of Stored procedure


DELIMITER $$
CREATE PROCEDURE addUser(IN CustomerID INT, IN Cname VARCHAR(25))
BEGIN
INSERT INTO customer(id,ename) VALUES(CustomerID,Cname);
END$$
2. Java Program: to insert record to the customer table into the faculty database
CallStateDemoInsert.java
package ProcedureStatement;
import java.sql.*;
public class CallStateDemoInsert {
public static void main(String[] args) {
Connection conn = null; CallableStatement stmt = null;
String url="jdbc:mysql://localhost:3309/faculty";
try{ Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(url,"root","rnsit");
//Create a Callable Statment
stmt = conn.prepareCall("{call addUser(?,?)}");
stmt.setInt(1, 103); // This would set ID as 103
stmt.setString(2, "Akshatha");

21 | 29
Module-4 JDBC

CallStateDemoInsert.java(Continued)
//Execute a stored procedure
int rs=stmt.executeUpdate();
if(rs==1)
System.out.println("Inserted Successfully ");
else
System.out.println("Fail to Insert record");
}
catch(SQLException | ClassNotFoundException se){
}
finally{
System.out.println("Goodbye!");
stmt.close(); conn.close();
}
}
}

1.8 Basic and Advanced JDBC data types:


The JDBC driver converts the Java data type to the appropriate JDBC type before sending it to the database. It
uses a default mapping for most data types.
For example: A Java int is converted to an SQL INTEGER. Default mappings were created to provide consistency
between drivers.
The following table summarizes the default JDBC data type that the Java data type is converted to when you call
the setXXX() method of the PreparedStatement or CallableStatement object or the ResultSet.updateXXX()
method.
setXX / getXX/
SQL JDBC/Java Description
updateXX
CHAR represents a small, fixed-length
setString () character string
CHAR
getString() VARCHAR represents a small, variable- length
VARCHAR java.lang.String
updateString() character string
LONGVARCHAR
LONGVARCHAR represents a large, variable-
length character string.
BINARY represents a small, fixed-length
BINARY setBytes() binary value.
VARBINARY represents a small, variable-length
VARBINARY byte[ ] getBytes()
binary value.
LONGVARBINARY updateBytes()
LONGVARBINARY represents a large, variable-
length binary value.

22 | 29
Module-4 JDBC

setXX / getXX/
SQL JDBC/Java Description
updateXX
setBoolean ()
represents a single bit value that can be zero or
BIT boolean getBoolean()
one.
updateBoolean()
setBigDecimal()
NUMERIC java.math.
getBigDecimal() Exact numerical (Same as DECIMAL)
DECIMAL BigDecimal
updateBigDecimal()
setByte () getByte() represents an 8-bit unsigned integer value
TINYINT byte
updateByte() between 0 and 255.
setShort() getShort() represents a 16-bit signed integer value between -
SMALLINT Short
updateShort() 32768 and 32767.
setInt() getInt() represents a a 32-bit signed integer value between
INTEGER Int
updateInt() - 2147483648 and 2147483647.
represents a 64-bit signed integer value between
setLong() getLong()
BIGINT Long -9223372036854775808 and
updateLong
9223372036854775807.
REAL setFloat() getFloat() REAL - a "single precision", 7 digits of mantissa.
Float
FLOAT updateFloat() FLOAT-"double precision", 15 digits of mantissa.
setDouble()
represents a "double precision" floating point
DOUBLE Double getDouble()
number which supports 15 digits of mantissa.
updateDouble()
setDate() getDate() 'YYYY-MM-DD’ format, supported range is
DATE java.sql.Date
updateDate() '1000-01-01' to '9999-12-31'.
'HH:MM:SS[millisecond]' format, range is
setTime() getTime ()
TIME java.sql.Time ‘-838:59:59.000000’ to ‘838:59:59.000000’
updateTime()
Millisecond represents in fractional value.
setTimestamp() 'YYYY-MM-DD 'HH:MM:SS[millisecond]'
TIMESTAMP java.sql.Timestamp getTimestamp() format, range is '1970-01-01 00:00:01.000000'
updateTimestamp() UTC to '2038-01-19 03:14:07.999999'
 Stands for “Character Large Object”
setClob() getClob()  is a data type that can be used to store a large
CLOB * java.sql.Clob
updateClob() amounts of character data in a database table
such as a plain text file
 Stands for “Binary Large Object”
 are used to store large amounts of binary data
setBlob() getBlob() in a database table, such as images, video,
BLOB* java.sql.Blob
updateBlob() png, mp3, mp4 or other types of files.
 The sorts and comparisons on the stored data
are case sensitive on BLOBs
Module-4 JDBC

setXX / getXX/
SQL JDBC/Java Description
updateXX
composite data value that consists of zero or more
setARRAY() elements of a specified data type
ARRAY* java.sql.Array getARRAY() Syntax:
updateARRAY()
data_type ARRAY[int] | VARARRAY[int]
setRef() getRef () Pointer that persistently denotes an instance of a
REF * java.sql.Ref
updateRef() structured type that resides in the database
SetStruct()
Container of ordered fields each with a type
STRUCT* java.sql.Struct getStruct()
(required) and field name (optional)
updateStruct()
Note: * indicate SQL3 data type supported in JDBC 2.

You might also like