SlideShare a Scribd company logo
Chapter Five
DATABASE ACCESS WITH JDBC
Objectives
❖ To become familiar with the JDBC API
❖ To learn how to load a driver, connect to a database, execute statements, and process result
sets using JDBC
❖ To use the prepared statements to execute precompiled SQL statements
Introduction of JDBC
JDBC is a Java database connectivity API.
Allows Java programs to contain database-independent code.
◦ Provides a mechanism for Java code to be portable across databases.
Simplifies the creation and execution of SQL statements.
Uses java.sql package.
◦ java.sql.DriverManager - Manages the loading and unloading of database drivers from the underlying system.
◦ java.sql.Connection - Handles the connection to a specific database.
◦ java.sql.Statement - Contains an SQL statement to be passed to the database.
◦ java.sql.ResultSet - Contains the record result set from the SQL statement passed to the database.
To connect to a database and access its contents, JDBC driver that works with that particular
database is required.
General structure of JDBC
How It Works
▪ Java code calls JDBC library
▪ JDBC loads a driver
▪ Driver talks to a particular database
▪ An application can work with several databases by using all corresponding
drivers
▪ Ideal: can change database engines without changing any application code
(not always in practice)
▪ The JDBC Classes and Interfaces are in the java.sql package
4
Application JDBC Driver
…
5
 JDBC consists of two parts:
 The JDBC API, a purely Java-
basedAPI
 JDBC Driver Manager,which
communicates with vendor-
specific drivers that interact
with the database
 translation to vendor format is
performed on the client
 No changes needed to server
 Driver (translator) needed on
client
Steps in Using JDBC
6
JDBC Class Usage
7
DriverManager
Driver
Connection
Statement
ResultSet
What are JDBC drivers?
 JDBC drivers implement the defined interfaces in the JDBC API for interacting with
your database server.
 For example, using JDBC drivers enable you to open database connections
and to interact with it by sending SQL or database commands then
receiving results with Java.
 Database vendors and third parties can produce them.
 Once you obtain a JDBC driver you should only have to worry about
registering it using DriverManager objects and creating the proper JDBC
URL in order to use it.
8
Java Model
9
JDBC driver types
 JDBC driver implementations vary because of the wide variety of operating systems and
hardware platforms in which Java operates.
 Thus, Sun has divided the implementation types into four categories, Types 1, 2, 3, and
4, whose characteristics vary greatly.
 Types 1 and 2 rely heavily on additional software (typically C/C++ DLLs) installed
on the client computer to provide database connectivity. Java and JDBC use these
components to interact with the database.
 Types 3 and 4 are pure Java implementations and require no additional software to be
installed on the client, except for the JDBC driver. Fortunately, packaging the JDBC
driver with your software distribution is trivial.
10
Type Description
1
JDBC-to-ODBC Bridge Driver – connects Java to a Microsoft ODBC (Open Database Connectivity) data
source.
2
Native-API, Part Java Drivers – enable JDBC programs to use database-specific APIs (normally written in
C or C++) that allow client programs to access databasesvia the Java Native Interface.
3
JDBC-Net Pure Java Drivers – take JDBC requests and translate them into a network protocol that is not
database specific. These requests are sent to a server, which translates the database requests into a database-
specific protocol.
4
Native-protocol Pure Java Drivers – convert JDBC requests to database-specific network protocols, so that
Java programs can connect directlyto a database.
JDBC Driver types
12
Some Popular JDBC Drivers
13
RDBMS JDBC Driver Name
MySQL
Driver Name
com.mysql.jdbc.Driver
Database URL format:
jdbc:mysql//hostname/databaseName
Oracle
Driver Name:
oracle.jdbc.driver.OracleDriver
Database URL format:
jdbc:oracle:thin@hostname:portnumber:databaseName
JavaDB
Driver Name:
org.apache.derby.jdbc.ClientDriver
Database URL format:
jdbc:derby://localhost:1527/databaseName
Access
Driver Name:
sun.jdbc.odbc.JdbcOdbcDriver
Database URL format:
jdbc:odbc:databaseName
Registering JDBC drivers
 To use your JDBC driver you must first register it with the DriverManager object, which
has a driver−registration method.
 However, two alternate techniques are available for registering JDBC drivers.
 The following is a list of the three different ways to register a JDBC driver:
 Class.forName(String driverName).newInstance()
-- Class.forName("com.mysql.jdbc.Driver").newInstance();
 DriverManager.registerDriver(Driver driverName)
-- Driver driver = new com.mysql.jdbc.Driver();
DriverManager.registerDriver(driver);
 jdbc.drivers property
-- System.setProperty("jdbc.drivers", "com.mysql.jdbc.Driver,oracle.jdbc.driver.OracleDriver");
14
15
Developing JDBC Programs
Loading
drivers
Establishing
connections
Creating and
executing
statements
Processing
ResultSet
Statement to load a driver:
Class.forName("JDBCDriverClass");
A driver is a class. For example:
Database
Access
MySQL
Oracle
Driver Class
sun.jdbc.odbc.JdbcOdbcDriver
com.mysql.jdbc.Driver
oracle.jdbc.driver.OracleDriver
Source
Already in JDK
Website
Website
The JDBC-ODBC driver for Access is bundled in JDK.
MySQL driver class is in mysqljdbc.jar
Oracle driver class is in classes12.jar
To use the MySQL and Oracle drivers, you have to add mysqljdbc.jar and
classes12.jar in the class path.
16
Developing JDBC Programs
Loading
drivers
Establishing
connections
Creating and
executing
statements
Processing
ResultSet
Connection connection = DriverManager.getConnection(databaseURL);
Database:
Access :
MySQL:
Oracle:
URL Pattern
jdbc:odbc:dataSource
jdbc:mysql://hostname:port# /dbname, username, password
jdbc:oracle:thin:@hostname:port#:oracleDBSID, username, pwd
Examples:
ForAccess:
Connection connection = DriverManager.getConnection
("jdbc:odbc:ExampleMDBDataSource");
For MySQL:
Connection connection = DriverManager.getConnection
("jdbc:mysql://localhost/test");
For Oracle:
Connection connection = DriverManager.getConnection
("jdbc:oracle:thin:@liang.armstrong.edu:1521:orcl", "scott", "tiger");
17
Developing JDBC Programs
Loading
drivers
Establishing
connections
Creatingand
executing
statements
Processing
ResultSet
Executing statement (for select):
// Select the columns from the Student table
ResultSet resultSet = stmt.executeQuery
("select firstName, mi, lastName from Student where lastName "
+ " = 'Smith'");
Processing ResultSet (for select):
// Iterate through the result and print the student names
while (resultSet.next())
System.out.println(resultSet.getString(1) + " " + resultSet.getString(2)
+ ". " + resultSet.getString(3));
18
Developing JDBC Programs
Loading
drivers
Establishing
connections
Creatingand
executing
statements
Processing
ResultSet
Creating statement:
Statement statement = connection.createStatement();
Executing statement (for update, delete,insert):
statement.executeUpdate ("create table Temp (col1 char(5),col2
char(5))");
Executing statement (for select):
// Select the columns from the Student table
ResultSet resultSet = statement.executeQuery
("select firstName, mi, lastName from Student where lastName "
+ " = 'Smith'");
19
Developing JDBC Programs
➢ The getString(1) , getString(2) , and getString(3) methods
retrieve the column values for firstName, mi ,and
lastName, respectively.
➢ Alternatively, you can use getString("firstName") ,
getString("mi") , and getString("lastName") to retrieve
the same three column values.
➢ The first execution of the next() method sets the current
row to the first row in the result set, and subsequent
invocations of the next() method set the current row to the
second row, third row, and so on, to the last row.
import java.sql.*;
public class SimpleJdbc {
public static void main(String[] args) throws SQLException, ClassNotFoundException
{
// Load the JDBC driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //not necessary for JDBC 4.0
System.out.println("Driver loaded");
// Establish a connection
Connection connection = DriverManager.getConnection ("jdbc:odbc:exampleMDBDataSource");
System.out.println("Database connected");
// Create a statement
Statement statement = connection.createStatement();
// Execute a statement
String query="select firstName, mi, lastName from Student where lastName = 'Smith'";
ResultSet resultSet = statement.executeQuery(query);
// Iterate through the result and print the student names
while (resultSet.next()) {
System.out.print(resultSet.getString(1) + "t“;
System.out.println(resultSet.getString(2) + "t" + resultSet.getString(3));
}
connection.close();
}
JDBC - Statements
➢ Once a connection is obtained we can interact with the database.
➢ The Statement interface provides methods to execute queries with
the database.
➢ The JDBC Statement, CallableStatement, and PreparedStatement
interfaces define the methods and properties that enable you to send
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.
21
JDBC - Statements
Interfeces Recommended use
Statement
Used to implement SQL statements with no
parameters.
PreparedStatement
Used for precompiling SQL statements that
might contain input parameters.
Callable Statement
Used to contain stored procedures that may
contain both input and output parameters
22
The Statement Objects
Creating Statement Object:
you need to create a statement using the
Connection object's createStatement( ) method, as
in the following example:
Closing Statement Object:
Just as you close a Connection object to save
database resources, for the same reason you
should also close the Statement object.
A simple call to the close() method will do the job.
23
The Statement Objects:
Once you've created a Statement object, you can then use it to execute a
SQL statement with one of its three execute methods which can accepts a
string containing a SQL statement as an argument.
1. boolean execute(String SQL) : Returns a boolean value of true if a ResultSet object can be
retrieved; otherwise, it returnsfalse.
2. int executeUpdate(String SQL) : Returns the numbers of rows affected by the execution of
the SQL statement. Use this method to execute SQL statements for which you expect to get a
number of rows affected - for example, an INSERT, UPDATE, or DELETE statement.
3. ResultSet executeQuery(String SQL) : Returns a ResultSet object. Use this method when
you expect to get a result set, as you would with a SELECT statement.
24
The execute(), executeQuery(),and executeUpdate() Methods
▪ The execute() method should be used if the execution produces multiple result
sets, multiple update counts, or a combination of result sets and update counts
▪ The executeQuery() method should be used if the execution produces a single
result set, such as the SQL select statement.
▪ The executeUpdate() method should be used if the statement results in a single
update count or no update count, such as a SQL INSERT, DELETE, UPDATE,
or DDL statement.
25
• PreparedStatement enables you to create parameterized SQL statements.
• Once a connection to a particular database is established, it can be used to send SQL
statements from your program to the database.
• The Statement interface is used to execute static SQL statements that don’t contain any
parameters.
• The PreparedStatement interface, extending Statement, is used to
execute a precompiled SQL statement with or without parameters.
• Since the SQL statements are precompiled, they are efficient for repeated executions.
• A PreparedStatement object is created using the preparedStatement
method in the Connection interface.
• For example, the following code creates a PreparedStatement for an SQL
insert statement:
• Statement preparedStatement = connection.prepareStatement ("insert into Student
(firstName, mi, lastName) " + "values (?, ?, ?)");
PreparedStatement
27
PreparedStatement
• This insert statement has threequestion marks as placeholdersfor parameters representing values for
firstName, mi , and lastName in a record of the Student table.
• As a sub-interfaceof Statement, the PreparedStatement interfaceinherits all the methods defined in
Statement.
• It also provides the methodsfor setting parameters in the object of PreparedStatement.
• These methods are used to set the values for the parameters before executing statementsor procedures.
In general, the set methodshave the following name and signature:
setX(int parameterIndex, X value);
• where X is the type of the parameter, and parameterIndex is the index of the parameter in
the statement. The index starts from 1.
• For example, the method setString(intparameterIndex, String value) sets a String value to the
specified parameter.
28
PreparedStatement
• The following statements pass the parameters "Jack", "A", and "Ryan” to the
placeholders for firstName, mi , and lastName in preparedStatement:
preparedStatement.setString(1, "Jack");
preparedStatement.setString(2, "A");
preparedStatement.setString(3, "Ryan");
• After setting the parameters, you can execute the prepared statement by invoking executeQuery() for a
SELECT statement and executeUpdate() for a DDL or update statement.
• The executeQuery() and executeUpdate() methods are similar to the ones defined in the Statement
interface except that they don’t have any parameters, because the SQL statements are already specified
in the preparedStatement method when the object of PreparedStatement is created.
…cont’d
…cont’d
Code to update data
PreparedStatement stmt=con.prepareStatement("update emp set name=?
where id=?");
stmt.setString(1,"Hana"); //1 specifies the first parameter in the query i.e. name
stmt.setInt(2,101);
int i=stmt.executeUpdate();
System.out.println(i+" records updated");
31
JDBC - Result Sets
➢ The SQL statements that read data from a database query return the data in a result set.
➢ The rows that satisfy a particular query are called the result set.
➢ A user can access the data in a result set using a cursor one row at a time from top to bottom
➢ The java.sql.ResultSet interface represents the result set of a database query.
➢ A ResultSet object maintains a cursor that points to the current row in the result set.
➢ ResultSet interface methods can be broken down into three categories:
◦ Navigationalmethods:used to move the cursor around.
◦ Get methods for viewing a result set: used to view the data in the columns of the current row being pointed
to by the cursor.
◦ Update methods: used to update the data in the columns of the current row. The updates can then be
updatedin the underlyingdatabase as well.
32
JDBC - Result Sets
Navigating a Result Set:
There are several methods in the ResultSet interface that involve moving the cursor, including:
S.N. Methods & Description
1
public void beforeFirst() throws SQLException
Moves the cursor to just before the first row
2
public void afterLast() throws SQLException
Moves the cursor to just after the last row
3
public boolean first() throws SQLException
Moves the cursor to the first row
4
public void last() throws SQLException
Moves the cursor to the last row.
5
public boolean absolute(int row) throws SQLException
Moves the cursor to the specified row
33
JDBC - Result Sets
Navigating a Result Set:
S.N. Methods & Description
6
public boolean relative(int row) throws SQLException
Moves the cursor the given number of rows forward or backwards from where it currently is pointing.
7
public boolean previous() throws SQLException
Moves the cursor to the previous row. This method returns false if the previous row is off the result set
8
public boolean next() throws SQLException
Moves the cursor to the next row. This method returns false if there are no more rows in the result set
9
public int getRow() throws SQLException
Returns the row number that the cursor is pointing to.
10
public void moveToInsertRow() throws SQLException
Moves the cursor to a special row in the result set that can be used to insert a new row into the database. The current cursor location is
remembered.
11
public void moveToCurrentRow() throws SQLException
Moves the cursor back to the current row if the cursor is currently at the insert row; otherwise, this method does nothing
34
JDBC - Result Sets
Viewing a Result Set:
The ResultSet interface contains dozensof methods for getting the data of the current row.
There is a get method for each of the possible data types, and each get method has two versions:
1. One that takes in a column name.
2. One that takes in a column index.
For example, if the column you are interested in viewing contains an int, you need to use one of the getInt()
methods of ResultSet:
S.N. Methods & Description
1
public int getInt(String columnName) throws SQLException
Returns the int in the current row in the column named columnName
2
public int getInt(int columnIndex) throws SQLException
Returns the int in the current row in the specified column index. The column index starts at 1,
meaning the first column of a row is 1, the second column of a row is 2, and so on.
35
JDBC - Result Sets
➢Similarly there are get methods in the ResultSet interface for each of the eight Java primitive types, as well as
common types such as java.lang.String, java.lang.Object, and java.net.URL
➢There are also methods for getting SQL data types java.sql.Date, java.sql.Time, java.sql.TimeStamp,
java.sql.Clob, and java.sql.Blob.
ResultSet Methods
String getString(int columnIndex)
boolean getBoolean(int columnIndex)
byte getByte(int columnIndex)
short getShort(int columnIndex)
int getInt(int columnIndex)
long getLong(int columnIndex)
float getFloat(int columnIndex)
double getDouble(int columnIndex)
Date getDate(int columnIndex)
Time getTime(int columnIndex)
Timestamp getTimestamp(int columnIndex)
JDBC - Result Sets
ResultSet Methods
isNull
◦ In SQL, NULL means the field is empty
◦ Not the same as 0 or “ ”
◦ In JDBC, you must explicitly ask if a field is null by calling ResultSet.isNull(column)
getMaxRows/setMaxRows
◦ Maximum number of rows a ResultSet may contain
◦ Unless explicitly set, the number of rows is unlimited
36
37
JDBC - Result Sets
Updating a Result Set:
The ResultSet interface contains a collectionof updatemethodsfor updatingthe data of a result set.
As with the get methods, there are two updatemethodsfor each data type:
1. One that takes in a column name.
2. One that takes in a column index.
For example, to updatea String column of the current row of a result set, you would use one of the
following updateString()methods:
S.N. Methods & Description
1
public void updateString(int columnIndex, String s) throws SQLException
Changes the String in the specified column to the value of s.
2
public void updateString(String columnName, String s) throws SQLException
Similar to the previous method, except that the column is specified by its name instead of its
index.
38
JDBC - Result Sets
Updating a Result Set:
There are update methods for the eight primitive data types, as well as String, Object, URL, and the SQL data types in the
java.sql package.
Updating a row in the result set changes the columns of the current row in the ResultSet object, but not in the underlying
database. To update your changes to the row in the database, you need to invoke one of the following methods.
S.N. Methods & Description
1
public void updateRow()
Updates the current row by updating the corresponding row in the database.
2
public void deleteRow()
Deletes the current row from the database
3
public void refreshRow()
Refreshes the data in the result set to reflect any recent changes in the database.
4
public void cancelRowUpdates()
Cancels any updates made on the current row.
5
public void insertRow()
Inserts a row into the database. This method can only be invoked when the cursor is pointing to the insert row.
Example code for updating a resultset and hence the database:
rs = st.executeQuery(“select * from emp”);
while(rs.next()){
if(rs.getString(“name”).equals(“Tom”)){
rs.updateString(“name”,“Tim”);
rs.updateRow();
}
}
//Example code for deleting a resultset and hence the database:
rs = st.executeQuery(“select * from emp”);
while(rs.next())
{
if(rs.getString(“name”).equals(“Tom”))
{
rs.deleteRow();
}
}
40
JDBC - Result Sets
➢ JDBC provides following connection methods to create statements with desired
ResultSet:
1. createStatement(int RSType, int RSConcurrency);
2. prepareStatement(String SQL, int RSType, int RSConcurrency);
3. prepareCall(String sql, int RSType, int RSConcurrency);
➢ The first argument indicate the type of a ResultSet object and the second argument
is one of two ResultSet constants for specifying whether a result set is read-only or
updatable.
JDBC - Result Sets
Type of ResultSet: The possible RSType are given below, If you do not specify any ResultSet type, you will
automatically get one that is TYPE_FORWARD_ONLY.
41
Type Description
ResultSet.TYPE_FORWARD_ONLY The cursor can only move forward in the result set.
ResultSet.TYPE_SCROLL_INSENSITIVE
The cursor can scroll forwards and backwards, and the
result set is not sensitive to changes made by others to
the database that occur after the result set was created.
ResultSet.TYPE_SCROLL_SENSITIVE.
The cursor can scroll forwards and backwards, and the
result set is sensitive to changes made by others to the
database that occur after the result set was created.
42
JDBC - Result Sets
Concurrency of ResultSet:
The possible RSConcurrency are given below, If you do not specify any Concurrency type, you will automatically get one
that is CONCUR_READ_ONLY.
Example:
try {
Statement stmt= conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
}
catch(Exception ex) { .... }
finally {....}
Concurrency Description
ResultSet.CONCUR_READ_ONLY Creates a read-onlyresult set. This is the default
ResultSet.CONCUR_UPDATABLE Creates an updateableresult set.
Batch Processing in JDBC
Instead of executing a single query, we can execute a batch (group) of queries.
It makes the performance fast. Allows you to group related statements into a batch and submit
them with one call to the database.
When you send several messages to the database at once, you reduce the amount of
communication overhead thereby improving performance.
The java.sql.Statement and java.sql.PreparedStatement interfaces provide methods for batch
processing.
Advantage of Batch Processing : Fast Performance
Batch Processing in JDBC
Methods of Statement interface
The required methods for batch processing are given below:
void addBatch(String query) - It adds query into batch.
int[] executeBatch() - It executes the batch of queries.
Example
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
con.setAutoCommit(false);
Statement stmt=con.createStatement();
stmt.addBatch("insert into emp values(190,'abhi',40000)");
stmt.addBatch("insert into emp values(191,'umesh',50000)");
stmt.executeBatch(); //executingthe batch
con.commit();
con.close();
CallableStatement
45
• The CallableStatementinterface is designed to execute SQL-storedprocedures.
• The proceduresmay have IN, OUT or IN OUTparameters.
• An IN parameter receives a value passed to the procedurewhen it is called.
• An OUT parameter returns a value after the procedure is completed, but it
doesn’tcontain any value when the procedure iscalled.
• An IN OUT parameter containsa value passed to the procedurewhen it is called,
and returns a value after it is completed.
• For example, thefollowing procedure in Oracle PL/SQL has IN parameter p1,
OUT parameter p2, and IN OUT parameterp3.
• create or replace procedure sampleProcedure (p1 in
varchar, p2 out number, p3 in out integer) is
begin
/* do something */
end sampleProcedure;
/
CallableStatement callableStatement = connection.prepareCall(callString);
46
≈ ∕∕ ≈
Ad

More Related Content

Similar to Chapter 5 JDBC.pdf for stufent of computer andtudent It s (20)

JDBC with MySQL.pdf
JDBC with MySQL.pdfJDBC with MySQL.pdf
JDBC with MySQL.pdf
Arumugam90
 
JDBC with MySQL.pdf
JDBC with MySQL.pdfJDBC with MySQL.pdf
JDBC with MySQL.pdf
Arumugam90
 
Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySql
Dhyey Dattani
 
Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySql
Dhyey Dattani
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
Vaishali Modi
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
Vaishali Modi
 
java database connection (jdbc)
java database connection (jdbc)java database connection (jdbc)
java database connection (jdbc)
Sanjay Gunjal
 
JDBC.ppt
JDBC.pptJDBC.ppt
JDBC.ppt
ChagantiSahith
 
jdbc Java Database Connectivity ujjwal matoliya jdbc.pptx
 jdbc Java Database Connectivity ujjwal matoliya jdbc.pptx jdbc Java Database Connectivity ujjwal matoliya jdbc.pptx
jdbc Java Database Connectivity ujjwal matoliya jdbc.pptx
ujjwalmatoliya
 
Introduction to Java Database Connectivity (JDBC)
Introduction to Java Database Connectivity (JDBC)Introduction to Java Database Connectivity (JDBC)
Introduction to Java Database Connectivity (JDBC)
Naresh IT
 
Final Database Connectivity in JAVA.ppt
Final Database Connectivity in JAVA.pptFinal Database Connectivity in JAVA.ppt
Final Database Connectivity in JAVA.ppt
TabassumMaktum
 
JDBC-Introduction
JDBC-IntroductionJDBC-Introduction
JDBC-Introduction
Mythili Shankar
 
Jdbc connectivity
Jdbc connectivityJdbc connectivity
Jdbc connectivity
arikazukito
 
JDBC Presentation with JAVA code Examples.pdf
JDBC Presentation with JAVA code Examples.pdfJDBC Presentation with JAVA code Examples.pdf
JDBC Presentation with JAVA code Examples.pdf
ssuser8878c1
 
java 4 Part 1 computer science.pptx
java 4 Part 1 computer science.pptxjava 4 Part 1 computer science.pptx
java 4 Part 1 computer science.pptx
MUHAMMED MASHAHIL PUKKUNNUMMAL
 
Jdbc
JdbcJdbc
Jdbc
haribee2000
 
JDBC
JDBCJDBC
JDBC
People Strategists
 
10 J D B C
10  J D B C10  J D B C
10 J D B C
guest04b824
 
4-INTERDUCATION TO JDBC-2019.ppt
4-INTERDUCATION TO JDBC-2019.ppt4-INTERDUCATION TO JDBC-2019.ppt
4-INTERDUCATION TO JDBC-2019.ppt
NaveenKumar648465
 
creating jdbc connection
creating jdbc connectioncreating jdbc connection
creating jdbc connection
Paneliya Prince
 
JDBC with MySQL.pdf
JDBC with MySQL.pdfJDBC with MySQL.pdf
JDBC with MySQL.pdf
Arumugam90
 
JDBC with MySQL.pdf
JDBC with MySQL.pdfJDBC with MySQL.pdf
JDBC with MySQL.pdf
Arumugam90
 
Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySql
Dhyey Dattani
 
Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySql
Dhyey Dattani
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
Vaishali Modi
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
Vaishali Modi
 
java database connection (jdbc)
java database connection (jdbc)java database connection (jdbc)
java database connection (jdbc)
Sanjay Gunjal
 
jdbc Java Database Connectivity ujjwal matoliya jdbc.pptx
 jdbc Java Database Connectivity ujjwal matoliya jdbc.pptx jdbc Java Database Connectivity ujjwal matoliya jdbc.pptx
jdbc Java Database Connectivity ujjwal matoliya jdbc.pptx
ujjwalmatoliya
 
Introduction to Java Database Connectivity (JDBC)
Introduction to Java Database Connectivity (JDBC)Introduction to Java Database Connectivity (JDBC)
Introduction to Java Database Connectivity (JDBC)
Naresh IT
 
Final Database Connectivity in JAVA.ppt
Final Database Connectivity in JAVA.pptFinal Database Connectivity in JAVA.ppt
Final Database Connectivity in JAVA.ppt
TabassumMaktum
 
Jdbc connectivity
Jdbc connectivityJdbc connectivity
Jdbc connectivity
arikazukito
 
JDBC Presentation with JAVA code Examples.pdf
JDBC Presentation with JAVA code Examples.pdfJDBC Presentation with JAVA code Examples.pdf
JDBC Presentation with JAVA code Examples.pdf
ssuser8878c1
 
4-INTERDUCATION TO JDBC-2019.ppt
4-INTERDUCATION TO JDBC-2019.ppt4-INTERDUCATION TO JDBC-2019.ppt
4-INTERDUCATION TO JDBC-2019.ppt
NaveenKumar648465
 
creating jdbc connection
creating jdbc connectioncreating jdbc connection
creating jdbc connection
Paneliya Prince
 

Recently uploaded (20)

Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Library Association of Ireland
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
SPRING FESTIVITIES - UK AND USA -
SPRING FESTIVITIES - UK AND USA            -SPRING FESTIVITIES - UK AND USA            -
SPRING FESTIVITIES - UK AND USA -
Colégio Santa Teresinha
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
Political History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptxPolitical History of Pala dynasty Pala Rulers NEP.pptx
Political History of Pala dynasty Pala Rulers NEP.pptx
Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 5-3-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 5-3-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
Quality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdfQuality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdf
Dr. Bindiya Chauhan
 
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 AccountingHow to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
Celine George
 
Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Library Association of Ireland
 
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Library Association of Ireland
 
2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx2541William_McCollough_DigitalDetox.docx
2541William_McCollough_DigitalDetox.docx
contactwilliamm2546
 
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
How to track Cost and Revenue using Analytic Accounts in odoo Accounting, App...
Celine George
 
Anti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptxAnti-Depressants pharmacology 1slide.pptx
Anti-Depressants pharmacology 1slide.pptx
Mayuri Chavan
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
Geography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjectsGeography Sem II Unit 1C Correlation of Geography with other school subjects
Geography Sem II Unit 1C Correlation of Geography with other school subjects
ProfDrShaikhImran
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar RabbiPresentation on Tourism Product Development By Md Shaifullar Rabbi
Presentation on Tourism Product Development By Md Shaifullar Rabbi
Md Shaifullar Rabbi
 
Metamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative JourneyMetamorphosis: Life's Transformative Journey
Metamorphosis: Life's Transformative Journey
Arshad Shaikh
 
Understanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s GuideUnderstanding P–N Junction Semiconductors: A Beginner’s Guide
Understanding P–N Junction Semiconductors: A Beginner’s Guide
GS Virdi
 
Quality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdfQuality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdf
Dr. Bindiya Chauhan
 
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 AccountingHow to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
How to Customize Your Financial Reports & Tax Reports With Odoo 17 Accounting
Celine George
 
Odoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo SlidesOdoo Inventory Rules and Routes v17 - Odoo Slides
Odoo Inventory Rules and Routes v17 - Odoo Slides
Celine George
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
P-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 finalP-glycoprotein pamphlet: iteration 4 of 4 final
P-glycoprotein pamphlet: iteration 4 of 4 final
bs22n2s
 
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Library Association of Ireland
 
Ad

Chapter 5 JDBC.pdf for stufent of computer andtudent It s

  • 2. Objectives ❖ To become familiar with the JDBC API ❖ To learn how to load a driver, connect to a database, execute statements, and process result sets using JDBC ❖ To use the prepared statements to execute precompiled SQL statements
  • 3. Introduction of JDBC JDBC is a Java database connectivity API. Allows Java programs to contain database-independent code. ◦ Provides a mechanism for Java code to be portable across databases. Simplifies the creation and execution of SQL statements. Uses java.sql package. ◦ java.sql.DriverManager - Manages the loading and unloading of database drivers from the underlying system. ◦ java.sql.Connection - Handles the connection to a specific database. ◦ java.sql.Statement - Contains an SQL statement to be passed to the database. ◦ java.sql.ResultSet - Contains the record result set from the SQL statement passed to the database. To connect to a database and access its contents, JDBC driver that works with that particular database is required.
  • 4. General structure of JDBC How It Works ▪ Java code calls JDBC library ▪ JDBC loads a driver ▪ Driver talks to a particular database ▪ An application can work with several databases by using all corresponding drivers ▪ Ideal: can change database engines without changing any application code (not always in practice) ▪ The JDBC Classes and Interfaces are in the java.sql package 4 Application JDBC Driver
  • 5. … 5  JDBC consists of two parts:  The JDBC API, a purely Java- basedAPI  JDBC Driver Manager,which communicates with vendor- specific drivers that interact with the database  translation to vendor format is performed on the client  No changes needed to server  Driver (translator) needed on client
  • 6. Steps in Using JDBC 6
  • 8. What are JDBC drivers?  JDBC drivers implement the defined interfaces in the JDBC API for interacting with your database server.  For example, using JDBC drivers enable you to open database connections and to interact with it by sending SQL or database commands then receiving results with Java.  Database vendors and third parties can produce them.  Once you obtain a JDBC driver you should only have to worry about registering it using DriverManager objects and creating the proper JDBC URL in order to use it. 8
  • 10. JDBC driver types  JDBC driver implementations vary because of the wide variety of operating systems and hardware platforms in which Java operates.  Thus, Sun has divided the implementation types into four categories, Types 1, 2, 3, and 4, whose characteristics vary greatly.  Types 1 and 2 rely heavily on additional software (typically C/C++ DLLs) installed on the client computer to provide database connectivity. Java and JDBC use these components to interact with the database.  Types 3 and 4 are pure Java implementations and require no additional software to be installed on the client, except for the JDBC driver. Fortunately, packaging the JDBC driver with your software distribution is trivial. 10
  • 11. Type Description 1 JDBC-to-ODBC Bridge Driver – connects Java to a Microsoft ODBC (Open Database Connectivity) data source. 2 Native-API, Part Java Drivers – enable JDBC programs to use database-specific APIs (normally written in C or C++) that allow client programs to access databasesvia the Java Native Interface. 3 JDBC-Net Pure Java Drivers – take JDBC requests and translate them into a network protocol that is not database specific. These requests are sent to a server, which translates the database requests into a database- specific protocol. 4 Native-protocol Pure Java Drivers – convert JDBC requests to database-specific network protocols, so that Java programs can connect directlyto a database.
  • 13. Some Popular JDBC Drivers 13 RDBMS JDBC Driver Name MySQL Driver Name com.mysql.jdbc.Driver Database URL format: jdbc:mysql//hostname/databaseName Oracle Driver Name: oracle.jdbc.driver.OracleDriver Database URL format: jdbc:oracle:thin@hostname:portnumber:databaseName JavaDB Driver Name: org.apache.derby.jdbc.ClientDriver Database URL format: jdbc:derby://localhost:1527/databaseName Access Driver Name: sun.jdbc.odbc.JdbcOdbcDriver Database URL format: jdbc:odbc:databaseName
  • 14. Registering JDBC drivers  To use your JDBC driver you must first register it with the DriverManager object, which has a driver−registration method.  However, two alternate techniques are available for registering JDBC drivers.  The following is a list of the three different ways to register a JDBC driver:  Class.forName(String driverName).newInstance() -- Class.forName("com.mysql.jdbc.Driver").newInstance();  DriverManager.registerDriver(Driver driverName) -- Driver driver = new com.mysql.jdbc.Driver(); DriverManager.registerDriver(driver);  jdbc.drivers property -- System.setProperty("jdbc.drivers", "com.mysql.jdbc.Driver,oracle.jdbc.driver.OracleDriver"); 14
  • 15. 15 Developing JDBC Programs Loading drivers Establishing connections Creating and executing statements Processing ResultSet Statement to load a driver: Class.forName("JDBCDriverClass"); A driver is a class. For example: Database Access MySQL Oracle Driver Class sun.jdbc.odbc.JdbcOdbcDriver com.mysql.jdbc.Driver oracle.jdbc.driver.OracleDriver Source Already in JDK Website Website The JDBC-ODBC driver for Access is bundled in JDK. MySQL driver class is in mysqljdbc.jar Oracle driver class is in classes12.jar To use the MySQL and Oracle drivers, you have to add mysqljdbc.jar and classes12.jar in the class path.
  • 16. 16 Developing JDBC Programs Loading drivers Establishing connections Creating and executing statements Processing ResultSet Connection connection = DriverManager.getConnection(databaseURL); Database: Access : MySQL: Oracle: URL Pattern jdbc:odbc:dataSource jdbc:mysql://hostname:port# /dbname, username, password jdbc:oracle:thin:@hostname:port#:oracleDBSID, username, pwd Examples: ForAccess: Connection connection = DriverManager.getConnection ("jdbc:odbc:ExampleMDBDataSource"); For MySQL: Connection connection = DriverManager.getConnection ("jdbc:mysql://localhost/test"); For Oracle: Connection connection = DriverManager.getConnection ("jdbc:oracle:thin:@liang.armstrong.edu:1521:orcl", "scott", "tiger");
  • 17. 17 Developing JDBC Programs Loading drivers Establishing connections Creatingand executing statements Processing ResultSet Executing statement (for select): // Select the columns from the Student table ResultSet resultSet = stmt.executeQuery ("select firstName, mi, lastName from Student where lastName " + " = 'Smith'"); Processing ResultSet (for select): // Iterate through the result and print the student names while (resultSet.next()) System.out.println(resultSet.getString(1) + " " + resultSet.getString(2) + ". " + resultSet.getString(3));
  • 18. 18 Developing JDBC Programs Loading drivers Establishing connections Creatingand executing statements Processing ResultSet Creating statement: Statement statement = connection.createStatement(); Executing statement (for update, delete,insert): statement.executeUpdate ("create table Temp (col1 char(5),col2 char(5))"); Executing statement (for select): // Select the columns from the Student table ResultSet resultSet = statement.executeQuery ("select firstName, mi, lastName from Student where lastName " + " = 'Smith'");
  • 19. 19 Developing JDBC Programs ➢ The getString(1) , getString(2) , and getString(3) methods retrieve the column values for firstName, mi ,and lastName, respectively. ➢ Alternatively, you can use getString("firstName") , getString("mi") , and getString("lastName") to retrieve the same three column values. ➢ The first execution of the next() method sets the current row to the first row in the result set, and subsequent invocations of the next() method set the current row to the second row, third row, and so on, to the last row.
  • 20. import java.sql.*; public class SimpleJdbc { public static void main(String[] args) throws SQLException, ClassNotFoundException { // Load the JDBC driver Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //not necessary for JDBC 4.0 System.out.println("Driver loaded"); // Establish a connection Connection connection = DriverManager.getConnection ("jdbc:odbc:exampleMDBDataSource"); System.out.println("Database connected"); // Create a statement Statement statement = connection.createStatement(); // Execute a statement String query="select firstName, mi, lastName from Student where lastName = 'Smith'"; ResultSet resultSet = statement.executeQuery(query); // Iterate through the result and print the student names while (resultSet.next()) { System.out.print(resultSet.getString(1) + "t“; System.out.println(resultSet.getString(2) + "t" + resultSet.getString(3)); } connection.close(); }
  • 21. JDBC - Statements ➢ Once a connection is obtained we can interact with the database. ➢ The Statement interface provides methods to execute queries with the database. ➢ The JDBC Statement, CallableStatement, and PreparedStatement interfaces define the methods and properties that enable you to send 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. 21
  • 22. JDBC - Statements Interfeces Recommended use Statement Used to implement SQL statements with no parameters. PreparedStatement Used for precompiling SQL statements that might contain input parameters. Callable Statement Used to contain stored procedures that may contain both input and output parameters 22
  • 23. The Statement Objects Creating Statement Object: you need to create a statement using the Connection object's createStatement( ) method, as in the following example: Closing Statement Object: Just as you close a Connection object to save database resources, for the same reason you should also close the Statement object. A simple call to the close() method will do the job. 23
  • 24. The Statement Objects: Once you've created a Statement object, you can then use it to execute a SQL statement with one of its three execute methods which can accepts a string containing a SQL statement as an argument. 1. boolean execute(String SQL) : Returns a boolean value of true if a ResultSet object can be retrieved; otherwise, it returnsfalse. 2. int executeUpdate(String SQL) : Returns the numbers of rows affected by the execution of the SQL statement. Use this method to execute SQL statements for which you expect to get a number of rows affected - for example, an INSERT, UPDATE, or DELETE statement. 3. ResultSet executeQuery(String SQL) : Returns a ResultSet object. Use this method when you expect to get a result set, as you would with a SELECT statement. 24
  • 25. The execute(), executeQuery(),and executeUpdate() Methods ▪ The execute() method should be used if the execution produces multiple result sets, multiple update counts, or a combination of result sets and update counts ▪ The executeQuery() method should be used if the execution produces a single result set, such as the SQL select statement. ▪ The executeUpdate() method should be used if the statement results in a single update count or no update count, such as a SQL INSERT, DELETE, UPDATE, or DDL statement. 25
  • 26. • PreparedStatement enables you to create parameterized SQL statements. • Once a connection to a particular database is established, it can be used to send SQL statements from your program to the database. • The Statement interface is used to execute static SQL statements that don’t contain any parameters. • The PreparedStatement interface, extending Statement, is used to execute a precompiled SQL statement with or without parameters. • Since the SQL statements are precompiled, they are efficient for repeated executions. • A PreparedStatement object is created using the preparedStatement method in the Connection interface. • For example, the following code creates a PreparedStatement for an SQL insert statement: • Statement preparedStatement = connection.prepareStatement ("insert into Student (firstName, mi, lastName) " + "values (?, ?, ?)"); PreparedStatement
  • 27. 27 PreparedStatement • This insert statement has threequestion marks as placeholdersfor parameters representing values for firstName, mi , and lastName in a record of the Student table. • As a sub-interfaceof Statement, the PreparedStatement interfaceinherits all the methods defined in Statement. • It also provides the methodsfor setting parameters in the object of PreparedStatement. • These methods are used to set the values for the parameters before executing statementsor procedures. In general, the set methodshave the following name and signature: setX(int parameterIndex, X value); • where X is the type of the parameter, and parameterIndex is the index of the parameter in the statement. The index starts from 1. • For example, the method setString(intparameterIndex, String value) sets a String value to the specified parameter.
  • 28. 28 PreparedStatement • The following statements pass the parameters "Jack", "A", and "Ryan” to the placeholders for firstName, mi , and lastName in preparedStatement: preparedStatement.setString(1, "Jack"); preparedStatement.setString(2, "A"); preparedStatement.setString(3, "Ryan"); • After setting the parameters, you can execute the prepared statement by invoking executeQuery() for a SELECT statement and executeUpdate() for a DDL or update statement. • The executeQuery() and executeUpdate() methods are similar to the ones defined in the Statement interface except that they don’t have any parameters, because the SQL statements are already specified in the preparedStatement method when the object of PreparedStatement is created.
  • 30. …cont’d Code to update data PreparedStatement stmt=con.prepareStatement("update emp set name=? where id=?"); stmt.setString(1,"Hana"); //1 specifies the first parameter in the query i.e. name stmt.setInt(2,101); int i=stmt.executeUpdate(); System.out.println(i+" records updated");
  • 31. 31 JDBC - Result Sets ➢ The SQL statements that read data from a database query return the data in a result set. ➢ The rows that satisfy a particular query are called the result set. ➢ A user can access the data in a result set using a cursor one row at a time from top to bottom ➢ The java.sql.ResultSet interface represents the result set of a database query. ➢ A ResultSet object maintains a cursor that points to the current row in the result set. ➢ ResultSet interface methods can be broken down into three categories: ◦ Navigationalmethods:used to move the cursor around. ◦ Get methods for viewing a result set: used to view the data in the columns of the current row being pointed to by the cursor. ◦ Update methods: used to update the data in the columns of the current row. The updates can then be updatedin the underlyingdatabase as well.
  • 32. 32 JDBC - Result Sets Navigating a Result Set: There are several methods in the ResultSet interface that involve moving the cursor, including: S.N. Methods & Description 1 public void beforeFirst() throws SQLException Moves the cursor to just before the first row 2 public void afterLast() throws SQLException Moves the cursor to just after the last row 3 public boolean first() throws SQLException Moves the cursor to the first row 4 public void last() throws SQLException Moves the cursor to the last row. 5 public boolean absolute(int row) throws SQLException Moves the cursor to the specified row
  • 33. 33 JDBC - Result Sets Navigating a Result Set: S.N. Methods & Description 6 public boolean relative(int row) throws SQLException Moves the cursor the given number of rows forward or backwards from where it currently is pointing. 7 public boolean previous() throws SQLException Moves the cursor to the previous row. This method returns false if the previous row is off the result set 8 public boolean next() throws SQLException Moves the cursor to the next row. This method returns false if there are no more rows in the result set 9 public int getRow() throws SQLException Returns the row number that the cursor is pointing to. 10 public void moveToInsertRow() throws SQLException Moves the cursor to a special row in the result set that can be used to insert a new row into the database. The current cursor location is remembered. 11 public void moveToCurrentRow() throws SQLException Moves the cursor back to the current row if the cursor is currently at the insert row; otherwise, this method does nothing
  • 34. 34 JDBC - Result Sets Viewing a Result Set: The ResultSet interface contains dozensof methods for getting the data of the current row. There is a get method for each of the possible data types, and each get method has two versions: 1. One that takes in a column name. 2. One that takes in a column index. For example, if the column you are interested in viewing contains an int, you need to use one of the getInt() methods of ResultSet: S.N. Methods & Description 1 public int getInt(String columnName) throws SQLException Returns the int in the current row in the column named columnName 2 public int getInt(int columnIndex) throws SQLException Returns the int in the current row in the specified column index. The column index starts at 1, meaning the first column of a row is 1, the second column of a row is 2, and so on.
  • 35. 35 JDBC - Result Sets ➢Similarly there are get methods in the ResultSet interface for each of the eight Java primitive types, as well as common types such as java.lang.String, java.lang.Object, and java.net.URL ➢There are also methods for getting SQL data types java.sql.Date, java.sql.Time, java.sql.TimeStamp, java.sql.Clob, and java.sql.Blob. ResultSet Methods String getString(int columnIndex) boolean getBoolean(int columnIndex) byte getByte(int columnIndex) short getShort(int columnIndex) int getInt(int columnIndex) long getLong(int columnIndex) float getFloat(int columnIndex) double getDouble(int columnIndex) Date getDate(int columnIndex) Time getTime(int columnIndex) Timestamp getTimestamp(int columnIndex)
  • 36. JDBC - Result Sets ResultSet Methods isNull ◦ In SQL, NULL means the field is empty ◦ Not the same as 0 or “ ” ◦ In JDBC, you must explicitly ask if a field is null by calling ResultSet.isNull(column) getMaxRows/setMaxRows ◦ Maximum number of rows a ResultSet may contain ◦ Unless explicitly set, the number of rows is unlimited 36
  • 37. 37 JDBC - Result Sets Updating a Result Set: The ResultSet interface contains a collectionof updatemethodsfor updatingthe data of a result set. As with the get methods, there are two updatemethodsfor each data type: 1. One that takes in a column name. 2. One that takes in a column index. For example, to updatea String column of the current row of a result set, you would use one of the following updateString()methods: S.N. Methods & Description 1 public void updateString(int columnIndex, String s) throws SQLException Changes the String in the specified column to the value of s. 2 public void updateString(String columnName, String s) throws SQLException Similar to the previous method, except that the column is specified by its name instead of its index.
  • 38. 38 JDBC - Result Sets Updating a Result Set: There are update methods for the eight primitive data types, as well as String, Object, URL, and the SQL data types in the java.sql package. Updating a row in the result set changes the columns of the current row in the ResultSet object, but not in the underlying database. To update your changes to the row in the database, you need to invoke one of the following methods. S.N. Methods & Description 1 public void updateRow() Updates the current row by updating the corresponding row in the database. 2 public void deleteRow() Deletes the current row from the database 3 public void refreshRow() Refreshes the data in the result set to reflect any recent changes in the database. 4 public void cancelRowUpdates() Cancels any updates made on the current row. 5 public void insertRow() Inserts a row into the database. This method can only be invoked when the cursor is pointing to the insert row.
  • 39. Example code for updating a resultset and hence the database: rs = st.executeQuery(“select * from emp”); while(rs.next()){ if(rs.getString(“name”).equals(“Tom”)){ rs.updateString(“name”,“Tim”); rs.updateRow(); } } //Example code for deleting a resultset and hence the database: rs = st.executeQuery(“select * from emp”); while(rs.next()) { if(rs.getString(“name”).equals(“Tom”)) { rs.deleteRow(); } }
  • 40. 40 JDBC - Result Sets ➢ JDBC provides following connection methods to create statements with desired ResultSet: 1. createStatement(int RSType, int RSConcurrency); 2. prepareStatement(String SQL, int RSType, int RSConcurrency); 3. prepareCall(String sql, int RSType, int RSConcurrency); ➢ The first argument indicate the type of a ResultSet object and the second argument is one of two ResultSet constants for specifying whether a result set is read-only or updatable.
  • 41. JDBC - Result Sets Type of ResultSet: The possible RSType are given below, If you do not specify any ResultSet type, you will automatically get one that is TYPE_FORWARD_ONLY. 41 Type Description ResultSet.TYPE_FORWARD_ONLY The cursor can only move forward in the result set. ResultSet.TYPE_SCROLL_INSENSITIVE The cursor can scroll forwards and backwards, and the result set is not sensitive to changes made by others to the database that occur after the result set was created. ResultSet.TYPE_SCROLL_SENSITIVE. The cursor can scroll forwards and backwards, and the result set is sensitive to changes made by others to the database that occur after the result set was created.
  • 42. 42 JDBC - Result Sets Concurrency of ResultSet: The possible RSConcurrency are given below, If you do not specify any Concurrency type, you will automatically get one that is CONCUR_READ_ONLY. Example: try { Statement stmt= conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY); } catch(Exception ex) { .... } finally {....} Concurrency Description ResultSet.CONCUR_READ_ONLY Creates a read-onlyresult set. This is the default ResultSet.CONCUR_UPDATABLE Creates an updateableresult set.
  • 43. Batch Processing in JDBC Instead of executing a single query, we can execute a batch (group) of queries. It makes the performance fast. Allows you to group related statements into a batch and submit them with one call to the database. When you send several messages to the database at once, you reduce the amount of communication overhead thereby improving performance. The java.sql.Statement and java.sql.PreparedStatement interfaces provide methods for batch processing. Advantage of Batch Processing : Fast Performance
  • 44. Batch Processing in JDBC Methods of Statement interface The required methods for batch processing are given below: void addBatch(String query) - It adds query into batch. int[] executeBatch() - It executes the batch of queries. Example Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:xe","system","oracle"); con.setAutoCommit(false); Statement stmt=con.createStatement(); stmt.addBatch("insert into emp values(190,'abhi',40000)"); stmt.addBatch("insert into emp values(191,'umesh',50000)"); stmt.executeBatch(); //executingthe batch con.commit(); con.close();
  • 45. CallableStatement 45 • The CallableStatementinterface is designed to execute SQL-storedprocedures. • The proceduresmay have IN, OUT or IN OUTparameters. • An IN parameter receives a value passed to the procedurewhen it is called. • An OUT parameter returns a value after the procedure is completed, but it doesn’tcontain any value when the procedure iscalled. • An IN OUT parameter containsa value passed to the procedurewhen it is called, and returns a value after it is completed. • For example, thefollowing procedure in Oracle PL/SQL has IN parameter p1, OUT parameter p2, and IN OUT parameterp3. • create or replace procedure sampleProcedure (p1 in varchar, p2 out number, p3 in out integer) is begin /* do something */ end sampleProcedure; / CallableStatement callableStatement = connection.prepareCall(callString);