SlideShare uma empresa Scribd logo
1 de 62
By
Ambarish Rai
Lovely Professional University, PunjabLovely Professional University, Punjab
Advanced Java Programming
Topic: JDBC
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Outlines
• Introduction
• Relational Database System
• JDBC
• JDBC Architecture
• JDBC Interfaces
• Prepared Statements
• Callable Statement
• Retrieving Metadata
• Scrollable and Updatable ResultSet
• Batch Processing
Introduction
Database System consists of :
1. A database
2. A software that stores and manages data in the database
3. Application programs that present the data and enable the
user to interact with the database system.
Application Programs
Database Management System
Database
Application User
System User
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Relational Database System
Based on Relational Data Model.
Key Components are:
1. Structure
2. Integrity
3. Language
Structure defines the representation of data.
Integrity imposes constraints on data.
Language provides means for accessing and manipulating the data.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Relational Structure
A Relation is a table consisting of non-duplicate rows.
A Row of a table represents a Record, and called as a Tuple.
A Column in a table represents an Attribute.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Integrity Constraints
An Integrity Constraint imposes a condition that all the legal
values in a table must satisfy.
Three types of Constraints are:
1. Domain Constraint
2. Primary Key Constraints
3. Foreign Key Constraints
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Integrity Constraints
Domain Constraints specify the permissible values for any attribute.
Primary Key Constraint: Primary Key is a minimal Super key, used
to identify a tuple in the database.
Foreign Key Constraint: defines the relationship among relations
(tables).
A set of attributes F is a foreign key in any relation R that references
relation T if:
1. The attributes in F have the same domain as the primary key in T.
2. A non-null value on F in R must match a primary key value in T.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
JDBC
JDBC stands for Java DataBase Connectivity.
JDBC is a standard Java API for database-independent
connectivity between the Java programming language and a
wide range of databases.
By using JDBC, a Java application can access any kind of
tabular data, especially data stored in a Relational Database.
JDBC works with Java on a variety of platforms, such as
Windows, Mac OS, and the various versions of UNIX.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
JDBC
• A JDBC based application is insulated from the
characteristics of specific database engines.
Java Application
JDBC
Access
Database
Oracle
Database
Sybase
Database
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Problem with Database Packages
Different Vendors provided Database Packages with different
APIs (functions defined for Application) in different
Technologies.
The Problem with native drivers was that a programmer has to
learn a new API for each Database and application needs to be
modified if database package is changed.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Database Packages and Application
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
ODBC
ODBC (Open DataBase Connectivity) provides the solution of
that problem.
It is a common API that is supported by all databases.
ODBC represents function prototype in C.
From Microsoft, 1994
Quite easy to use (preferred in .Net)…
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
ODBC
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
JDBC’s design is very similar to the design of ODBC.
Database vendors provide JDBC drivers for the database
package.
JDBC helps in writing Java applications that manage these
three programming activities:
Connect to a data source, like a database
Send queries and update statements to the database
Retrieve and process the results received from the database
in answer to our query
JDBC Concepts
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
JDBC Concepts
Driver Manager
Loads database drivers, and manages the connection between
the application and the driver
Driver
Translates API calls into operations for a specific data source
Connection
A session between an application and a database
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
JDBC Concepts
Statement
An SQL Statement to perform a query or update operation
Metadata
Information about returned data, the database and the driver
ResultSet
Logical set of columns and rows returned by executing an
SQL statement (resulting tuples)
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Steps during Execution
The following steps are executed when running a JDBC application
Import the necessary classes
Load the JDBC driver
Identify the database source
Allocate a “connection” object (create)
Allocate a “Statement” object (create)
Execute a query using the “Statement” object
Retrieve data from the returned “ResultSet” object
Close the “ResultSet” object
Close the “Statement” object
Close the “Connection” object
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
JDBC Component Interaction
Driver
Manager Connection Statement ResultSet
Driver
Database
Creates Creates Creates
SQL
Result
(tuples)
Establish
Link to DB
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Steps Involved in Basic JDBC Operations
Driver
Driver Manager
Connection
Statement
Result Set
1. Load the JDBC driver class:
Class.forName(“driverName”);
2. Open a database connection:
DriverManager.getConnection
(“jdbc:xxx:datasource”);
3. Issue SQL statements:
stmt = con.createStatement();
stmt.executeQuery (“Select * from myTable”);
4. Process resultset:
while (rs.next()) {
name = rs.getString(“name”);
amount = rs.getInt(“amt”); }
Database
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
JDBC ARCHITECTURE
Two-Tier Database Access Model
Java Application talks
directly to the database.
Accomplished through the
JDBC driver which sends
commands directly to the
database.
Results sent back directly to
the application
Application Space
Java Application
JDBC Driver
Database
SQL
Command
Result
Set
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Three-Tier Database Access Model
JDBC driver sends
commands to a middle
tier, which in turn sends
commands to database.
Results are sent back to
the middle tier, which
communicates them
back to the application
Application Space
Java Application
JDBC Driver
Database
SQL
Command
Result
Set
Application Server
(middle-tier)
Proprietary
Protocol
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
JDBC DRIVERS
JDBC Driver Types
JDBC-ODBC Bridge, plus ODBC driver (Type 1)
JDBC methods -> Translate JDBC methods to ODBC methods ->
ODBC to native methods -> Native methods API
Native-API, partly Java driver (Type 2)
JDBC methods -> Map JDBC methods to native methods (calls to
vendor library) -> Native methods API (vendor library)
JDBC-Network driver (Type 3)
JDBC methods -> Translate to Native API methods through
TCP/IP network -> Native API methods
Pure Java driver (Type 4)
Java methods -> Native methods in Java
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Type 1: JDBC-ODBC Bridge
This driver type is provided by Sun
with JDK
Provides JDBC access to databases
through ODBC drivers
ODBC driver must be configured
for the bridge to work
Only solution if no JDBC driver
available for the DBMS
Application Space
Java Application
JDBC – ODBC Bridge
Database
SQL
Command
Result
Set
ODBC Driver
Proprietary
Protocol
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Type 2: Native-API, Partly Java Driver
Native-API driver converts
JDBC commands into DBMS-
specific native calls
Directly interfaces with the
database
Application Space
Java Application
Type 2 JDBC Driver
Database
SQL
Command
Result
Set
Native
Database
Library
Proprietary
Protocol
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Type 3: JDBC-Network Driver
Translates JDBC calls into a
database-independent network
protocol and sent to a middleware
server.
This server translates this DBMS-
independent protocol into a DBMS-
specific protocol and sent to the
database.
Results sent back to the middleware
and routed to the client
Application Space
Java Application
Type 3 JDBC Driver
Database
SQL
Command
Result
Set
Middleware Space
Proprietary
Protocol
JDBC Driver
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Type 4: Native-Protocol, Pure Java Driver
Pure Java drivers that
communicate directly with the
vendor’s database
JDBC commands converted to
database engine’s native protocol
directly
Advantage: no additional
translation or middleware layer
Improves performance
Application Space
Java Application
Type 4 JDBC Driver
Database
SQL Command
Using Proprietary
Protocol
Result Set
Using Proprietary
Protocol
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Driver Manager
The DriverManager class is responsible for establishing connections
to the data sources, accessed through the JDBC drivers.
The driver can be loaded explicitly by calling the static method
“forName” in the “Class” class and pass the driver argument
Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”);
The “forName()” method can throw a “ClassNotFoundException” if
the driver class is not found. Hence, this function call should be in a
try-catch block.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Connection Object
Connection object represents an established connection to a particular
data source
A connection object can also be used to query the data source (data and
metadata)
Different versions of getConnection() method contained in the
DriverManager class that returns a connection object:
Connection con = DriverManager.getConnection(source);
Connection con = DriverManager.getConnection(source, u_name, pwd);
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Statement Object
Used for creating an SQL query, execute it, and retrieve the results.
Statement objects are created by calling the createStatement() method of a
valid connection object.
Executes SQL query by calling the executeQuery() method.
The SQL query string is passed as argument to the executeQuery() method
The result of executing the query is returned as an object of type
“ResultSet”
Statement stmt = con.createStatement();
ResultSet myresults = stmt.executeQuery(“select * from authors”);
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
ResultSet Object
The results of executing an SQL query are returned in the form of an
object that implements the ResultSet interface.
ResultSet object contains a “cursor” that points to a particular record
(called the current record).
When the ResultSet object is created, the cursor points to the position
immediately preceding the first record.
Several methods available to navigate the ResultSet by moving the
cursor:
first(), last(), beforeFirst(), afterLast(), next(), previous(), etc.
//returns true if the move is successful
isFirst() //whether you reached the beginning of the ResultSet
isLast() // whether you reached the end of the ResultSet
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Accessing Data in a ResultSet
Methods for Retrieving Column Data:
getString(), getInt(), getShort(), getFloat(), getDouble(),
getTime() etc.
We can always use getString() method for numerical values if we
are not going to do some computations.
Column names are NOT case sensitive.
ResultSetMetaData object has metadata information about
records, i.e., column names, data types etc.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Statement
Statement
Defines the methods and properties that enable us to send SQL or
PL/SQL commands and receive data from database.
Statement: Useful when we are using static SQL statements at runtime.
-- The Statement interface cannot accept parameters.
PreparedStatement: Used when we plan to use the SQL statements
many times.
-- The PreparedStatement interface accepts input parameters at runtime.
CallableStatement: Used when we want to access database stored
procedures.
-- The CallableStatement interface can also accept runtime input
parameters.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Statement Methods
boolean execute(String SQL): Returns a boolean value of true if a
ResultSet object can be retrieved; otherwise, it returns false.
-- Use this method to execute SQL DDL statements.
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.
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.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
PreparedStatement
The PreparedStatement interface extends the Statement interface.
PreparedStatement provides the facility of executing parameterized
query.
prepareStatement() method of Connection interface is used to create
a prepared Statement.
Statement pstmt = con.prepareStatement(“insert into Emp (id,
name, age)” + “values (?, ?, ?)”);
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
It also provides methods for setting the parameters in the
preparedStatement object.
General method Signature:
setXXX (int parameterIndex, X value)
pstmt.setInt (1, 30)
pstmt.setString (2, “Ravi Kant”)
pstmt.setInt (3, 26)
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
PreparedStatement Methods
CallableStatement interface is used to execute SQL-stored
procedures.
A CallableStatement object can be created using the prepareCall
(String call) method.
CallableStatement cstmt = con.prepareCall
(“{call sampleProcedure(?, ?, ?)}”);
CallableStatement for a function:
CallableStatement cstmt = con.prepareCall
(“{? = call sampleProcedure(?, ?, ?)}”);
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
CallableStatement
create or replace procedure sampleProcedure
(p1 in varchar, p2 out number, p3 in out integer) is
begin
-- do something
end sampleProcedure;
Parameters: PreparedStatement uses only IN parameter, while
CallableStatement uses all three.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
StoredProcedure
Setting IN Parameter:
setXXX (int parameterIndex, X value)
cstmt.setInt (1, 30)
cstmt.setString (2, “Ravi Kant”)
Setting OUT Parameter:
registerOutParameter (int parameterIndex, Types.XXX)
-- Types.INTEGER, Types.DOUBLE etc
cstmt.registerOutParameter (3, Types.INTEGER);
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
CallableStatement Methods
Resultset
ResultSet
A ResultSet object maintains a cursor pointing to its current
row of data.
Initially the cursor is positioned before the first row.
The next method moves the cursor to the next row, and returns
false when there are no more rows in the ResultSet object.
A default ResultSet object is not updatable and has a cursor
that moves forward only.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Scrollable and Updateable Resultset
With the new versions of JDBC, we can scroll the rows both forward
and backward and move the cursor to a desired location using the
first(), last(), next(), previous(), absolute(), or relative() method.
We can insert, delete, or update a row in the result set and have the
changes automatically reflected in the database.
To obtain a scrollable or updatable result set, first create a statement
with an appropriate type and concurrency mode.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Scrollable and Updateable Resultset
For static statement,
Statement statement = connection.createStatement (
int resultSetType,
int resultSetConcurrency);
For a prepared statement,
PreparedStatement statement = connection.prepareStatement(
String sql,
int resultSetType,
int resultSetConcurrency);
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Scrollable Resultset
The possible values of resultSetType are the constants defined in the
ResultSet:
TYPE_FORWARD_ONLY: The result set is accessed forward
sequentially.
TYPE_SCROLL_INSENSITIVE: The result set is scrollable, but not
sensitive to changes in the database.
TYPE_SCROLL_SENSITIVE: The result set is scrollable and sensitive
to changes made by others.
Use this type if you want the result set to be scrollable and updatable.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Updateable Resultset
The possible values of resultSetConcurrency are the constants defined in
the ResultSet:
CONCUR_READ_ONLY: The result set cannot be used to update the
database.
CONCUR_UPDATABLE: The result set can be used to update the
database.
For example, scrollable and updatable resultset can be created as
follows:
Statement statement = connection.createStatement
(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE)
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Retrieving MetaData
MetaData
JDBC provides two interfaces for obtaining metadata.
DatabaseMetaData interface for obtaining database information.
ResultSetMetaData interface for obtaining information of specific
ResultSet (e.g. column count and column names).
getMetaData() method is used to obtain the metadata.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
DatabaseMetaData
Following methods can be used to obtain database metadata:
1. getUserName()
2. getURL()
3. getDatabaseProductName()
4. getDatabaseProductVersion()
5. getDriverName()
6. getDriverVersion()
7. getDriverMajorVersion()
8. getDriverMinorVersion()
9. getMaxConnections()
10. getMaxTableNameLength()
11. getMaxColumnsInTable()
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
ResultSetMetaData
It provides the following methods:
1. getColumnName(int) method to find the column names.
2. getColumnCount() method to find the number of columns in the
resultset.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Batch Processing
Batch Processing
Batch Processing allows to group related SQL statements into a batch
and submit them with one call to the database.
When we send several SQL statements to the database at once, it
reduces the amount of communication overhead, thereby improving
performance.
DatabaseMetaData.supportsBatchUpdates() method is used to determine if
the target database supports batch update processing.
The method returns true if JDBC driver supports this feature.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Methods for Batch Processing
The addBatch() method is used to add individual statements to the batch.
The executeBatch() is used to start the execution of all the statements
grouped together.
The executeBatch() returns an array of integers, and each element of the
array represents the update count for the respective update statement.
The clearBatch() method is used to remove all the statements added with
the addBatch() method.
We can not selectively choose which statement to remove.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Steps to use Batch Processing
Create a Statement object using createStatement() methods.
Set auto-commit to false using setAutoCommit().
Add as many as SQL statements you like into batch using addBatch()
method on created statement object.
Execute all the SQL statements using executeBatch() method on created
statement object.
Finally, commit all the changes using commit() method.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Example
// Create statement object
Statement stmt = conn.createStatement();
// Set auto-commit to false
conn.setAutoCommit(false);
// Create some SQL statements and add them in the batch
String SQL = "INSERT INTO Emp (id, name, age) " + "VALUES(1,‘Ravi’, 25)";
stmt.addBatch(SQL);
String SQL = "INSERT INTO Emp (id, name, age) " + "VALUES(200,'Raj', 30)";
stmt.addBatch(SQL);
String SQL = "UPDATE Emp SET age = 35 " + "WHERE id = 100";
stmt.addBatch(SQL);
// Create an int[] to hold returned values
int[] count = stmt.executeBatch();
//Explicitly commit statements to apply changes
conn.commit();
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
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 Driver Class Source
Access sun.jdbc.odbc.JdbcOdbcDriver Already in
JDK
MySQL com.mysql.jdbc.Driver Website
Oracle oracle.jdbc.driver.OracleDriver 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
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Developing JDBC Programs
Loading drivers
Establishing
connections
Creating and
executing
statements
Processing
ResultSet
Connection connection = DriverManager.getConnection(databaseURL);
Database URL Pattern
Access jdbc:odbc:dataSource
MySQL jdbc:mysql://hostname/dbname
Oracle jdbc:oracle:thin:@hostname:port#:oracleDBSID
Examples:
For Access:
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");
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Developing JDBC Programs
Loading drivers
Establishing
connections
Creating and
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'");
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Developing JDBC Programs
Loading
drivers
Establishing
connections
Creating and
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));
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
JDBC connectivity with Oracle
Oracle JDBC Thin Driver Format:
jdbc:oracle:thin:@<host>:<port>:<SID>
jdbc:oracle:thin:@//<host>:<port>/<service_name>
Example:
jdbc:oracle:thin:192.168.2.1:1521:X01A
jdbc:oracle:thin:@//192.168.2.1:1521/XE
The Oracle System ID (SID) is used to uniquely identify a particular
database on a system. For this reason, one cannot have more than one
database with the same SID on a computer system.
Note: Support for SID is being phased out.
Oracle recommends that users switch over to using service names.
Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
Jdbc slide for beginers

Mais conteúdo relacionado

Mais procurados

Mais procurados (20)

Jdbc
JdbcJdbc
Jdbc
 
Ajp notes-chapter-05
Ajp notes-chapter-05Ajp notes-chapter-05
Ajp notes-chapter-05
 
Jdbc ppt
Jdbc pptJdbc ppt
Jdbc ppt
 
Java- JDBC- Mazenet Solution
Java- JDBC- Mazenet SolutionJava- JDBC- Mazenet Solution
Java- JDBC- Mazenet Solution
 
Jdbc_ravi_2016
Jdbc_ravi_2016Jdbc_ravi_2016
Jdbc_ravi_2016
 
JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...
JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...
JDBC,Types of JDBC,Resultset, statements,PreparedStatement,CallableStatements...
 
Jdbc
JdbcJdbc
Jdbc
 
Jdbc
JdbcJdbc
Jdbc
 
Jdbc connectivity in java
Jdbc connectivity in javaJdbc connectivity in java
Jdbc connectivity in java
 
Jdbc drivers
Jdbc driversJdbc drivers
Jdbc drivers
 
JDBC
JDBCJDBC
JDBC
 
Java Database Connectivity
Java Database ConnectivityJava Database Connectivity
Java Database Connectivity
 
jdbc document
jdbc documentjdbc document
jdbc document
 
Jdbc architecture and driver types ppt
Jdbc architecture and driver types pptJdbc architecture and driver types ppt
Jdbc architecture and driver types ppt
 
java jdbc connection
java jdbc connectionjava jdbc connection
java jdbc connection
 
Java database connectivity
Java database connectivityJava database connectivity
Java database connectivity
 
Jdbc
JdbcJdbc
Jdbc
 
Jdbc
JdbcJdbc
Jdbc
 
Database and Java Database Connectivity
Database and Java Database ConnectivityDatabase and Java Database Connectivity
Database and Java Database Connectivity
 
Jdbc
JdbcJdbc
Jdbc
 

Semelhante a Jdbc slide for beginers

creating jdbc connection
creating jdbc connectioncreating jdbc connection
creating jdbc connectionPaneliya Prince
 
creating jdbc connection
creating jdbc connectioncreating jdbc connection
creating jdbc connectionPaneliya Prince
 
JDBC with MySQL.pdf
JDBC with MySQL.pdfJDBC with MySQL.pdf
JDBC with MySQL.pdfArumugam90
 
JDBC with MySQL.pdf
JDBC with MySQL.pdfJDBC with MySQL.pdf
JDBC with MySQL.pdfArumugam90
 
Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySqlDhyey Dattani
 
Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySqlDhyey Dattani
 
Fundamentals of JDBC
Fundamentals of JDBCFundamentals of JDBC
Fundamentals of JDBCJainul Musani
 
JDBC : Java Database Connectivity
JDBC : Java Database Connectivity JDBC : Java Database Connectivity
JDBC : Java Database Connectivity DevAdnani
 
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.pptxujjwalmatoliya
 
1. java database connectivity (jdbc)
1. java database connectivity (jdbc)1. java database connectivity (jdbc)
1. java database connectivity (jdbc)Fad Zulkifli
 
JDBC java for learning java for learn.ppt
JDBC java for learning java for learn.pptJDBC java for learning java for learn.ppt
JDBC java for learning java for learn.pptkingkolju
 
Introduction to JDBC and JDBC Drivers
Introduction to JDBC and JDBC DriversIntroduction to JDBC and JDBC Drivers
Introduction to JDBC and JDBC DriversKumar
 

Semelhante a Jdbc slide for beginers (20)

Computer Science:Java jdbc
Computer Science:Java jdbcComputer Science:Java jdbc
Computer Science:Java jdbc
 
Core jdbc basics
Core jdbc basicsCore jdbc basics
Core jdbc basics
 
creating jdbc connection
creating jdbc connectioncreating jdbc connection
creating jdbc connection
 
creating jdbc connection
creating jdbc connectioncreating jdbc connection
creating jdbc connection
 
JDBC-Introduction
JDBC-IntroductionJDBC-Introduction
JDBC-Introduction
 
JDBC with MySQL.pdf
JDBC with MySQL.pdfJDBC with MySQL.pdf
JDBC with MySQL.pdf
 
JDBC with MySQL.pdf
JDBC with MySQL.pdfJDBC with MySQL.pdf
JDBC with MySQL.pdf
 
Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySql
 
Java database connectivity with MySql
Java database connectivity with MySqlJava database connectivity with MySql
Java database connectivity with MySql
 
Fundamentals of JDBC
Fundamentals of JDBCFundamentals of JDBC
Fundamentals of JDBC
 
Rajesh jdbc
Rajesh   jdbcRajesh   jdbc
Rajesh jdbc
 
Jdbc introduction
Jdbc introductionJdbc introduction
Jdbc introduction
 
3 jdbc
3 jdbc3 jdbc
3 jdbc
 
JDBC : Java Database Connectivity
JDBC : Java Database Connectivity JDBC : Java Database Connectivity
JDBC : Java Database Connectivity
 
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
 
Assignment#10
Assignment#10Assignment#10
Assignment#10
 
1. java database connectivity (jdbc)
1. java database connectivity (jdbc)1. java database connectivity (jdbc)
1. java database connectivity (jdbc)
 
JDBC java for learning java for learn.ppt
JDBC java for learning java for learn.pptJDBC java for learning java for learn.ppt
JDBC java for learning java for learn.ppt
 
Unit 5.pdf
Unit 5.pdfUnit 5.pdf
Unit 5.pdf
 
Introduction to JDBC and JDBC Drivers
Introduction to JDBC and JDBC DriversIntroduction to JDBC and JDBC Drivers
Introduction to JDBC and JDBC Drivers
 

Último

Virtual memory management in Operating System
Virtual memory management in Operating SystemVirtual memory management in Operating System
Virtual memory management in Operating SystemRashmi Bhat
 
System Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event SchedulingSystem Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event SchedulingBootNeck1
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...asadnawaz62
 
Work Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvWork Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvLewisJB
 
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor CatchersTechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catcherssdickerson1
 
Industrial Safety Unit-IV workplace health and safety.ppt
Industrial Safety Unit-IV workplace health and safety.pptIndustrial Safety Unit-IV workplace health and safety.ppt
Industrial Safety Unit-IV workplace health and safety.pptNarmatha D
 
Autonomous emergency braking system (aeb) ppt.ppt
Autonomous emergency braking system (aeb) ppt.pptAutonomous emergency braking system (aeb) ppt.ppt
Autonomous emergency braking system (aeb) ppt.pptbibisarnayak0
 
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfgUnit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfgsaravananr517913
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionDr.Costas Sachpazis
 
Research Methodology for Engineering pdf
Research Methodology for Engineering pdfResearch Methodology for Engineering pdf
Research Methodology for Engineering pdfCaalaaAbdulkerim
 
Ch10-Global Supply Chain - Cadena de Suministro.pdf
Ch10-Global Supply Chain - Cadena de Suministro.pdfCh10-Global Supply Chain - Cadena de Suministro.pdf
Ch10-Global Supply Chain - Cadena de Suministro.pdfChristianCDAM
 
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTIONTHE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTIONjhunlian
 
Indian Dairy Industry Present Status and.ppt
Indian Dairy Industry Present Status and.pptIndian Dairy Industry Present Status and.ppt
Indian Dairy Industry Present Status and.pptMadan Karki
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024Mark Billinghurst
 
Crystal Structure analysis and detailed information pptx
Crystal Structure analysis and detailed information pptxCrystal Structure analysis and detailed information pptx
Crystal Structure analysis and detailed information pptxachiever3003
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)Dr SOUNDIRARAJ N
 
welding defects observed during the welding
welding defects observed during the weldingwelding defects observed during the welding
welding defects observed during the weldingMuhammadUzairLiaqat
 
11. Properties of Liquid Fuels in Energy Engineering.pdf
11. Properties of Liquid Fuels in Energy Engineering.pdf11. Properties of Liquid Fuels in Energy Engineering.pdf
11. Properties of Liquid Fuels in Energy Engineering.pdfHafizMudaserAhmad
 

Último (20)

Virtual memory management in Operating System
Virtual memory management in Operating SystemVirtual memory management in Operating System
Virtual memory management in Operating System
 
System Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event SchedulingSystem Simulation and Modelling with types and Event Scheduling
System Simulation and Modelling with types and Event Scheduling
 
complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...complete construction, environmental and economics information of biomass com...
complete construction, environmental and economics information of biomass com...
 
Work Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvvWork Experience-Dalton Park.pptxfvvvvvvv
Work Experience-Dalton Park.pptxfvvvvvvv
 
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor CatchersTechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
TechTAC® CFD Report Summary: A Comparison of Two Types of Tubing Anchor Catchers
 
Industrial Safety Unit-IV workplace health and safety.ppt
Industrial Safety Unit-IV workplace health and safety.pptIndustrial Safety Unit-IV workplace health and safety.ppt
Industrial Safety Unit-IV workplace health and safety.ppt
 
Designing pile caps according to ACI 318-19.pptx
Designing pile caps according to ACI 318-19.pptxDesigning pile caps according to ACI 318-19.pptx
Designing pile caps according to ACI 318-19.pptx
 
Autonomous emergency braking system (aeb) ppt.ppt
Autonomous emergency braking system (aeb) ppt.pptAutonomous emergency braking system (aeb) ppt.ppt
Autonomous emergency braking system (aeb) ppt.ppt
 
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfgUnit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
Unit7-DC_Motors nkkjnsdkfnfcdfknfdgfggfg
 
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective IntroductionSachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
Sachpazis Costas: Geotechnical Engineering: A student's Perspective Introduction
 
Research Methodology for Engineering pdf
Research Methodology for Engineering pdfResearch Methodology for Engineering pdf
Research Methodology for Engineering pdf
 
Ch10-Global Supply Chain - Cadena de Suministro.pdf
Ch10-Global Supply Chain - Cadena de Suministro.pdfCh10-Global Supply Chain - Cadena de Suministro.pdf
Ch10-Global Supply Chain - Cadena de Suministro.pdf
 
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTIONTHE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
THE SENDAI FRAMEWORK FOR DISASTER RISK REDUCTION
 
Indian Dairy Industry Present Status and.ppt
Indian Dairy Industry Present Status and.pptIndian Dairy Industry Present Status and.ppt
Indian Dairy Industry Present Status and.ppt
 
IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024IVE Industry Focused Event - Defence Sector 2024
IVE Industry Focused Event - Defence Sector 2024
 
Crystal Structure analysis and detailed information pptx
Crystal Structure analysis and detailed information pptxCrystal Structure analysis and detailed information pptx
Crystal Structure analysis and detailed information pptx
 
Design and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdfDesign and analysis of solar grass cutter.pdf
Design and analysis of solar grass cutter.pdf
 
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
UNIT III ANALOG ELECTRONICS (BASIC ELECTRONICS)
 
welding defects observed during the welding
welding defects observed during the weldingwelding defects observed during the welding
welding defects observed during the welding
 
11. Properties of Liquid Fuels in Energy Engineering.pdf
11. Properties of Liquid Fuels in Energy Engineering.pdf11. Properties of Liquid Fuels in Energy Engineering.pdf
11. Properties of Liquid Fuels in Energy Engineering.pdf
 

Jdbc slide for beginers

  • 1. By Ambarish Rai Lovely Professional University, PunjabLovely Professional University, Punjab Advanced Java Programming Topic: JDBC
  • 2. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India) Outlines • Introduction • Relational Database System • JDBC • JDBC Architecture • JDBC Interfaces • Prepared Statements • Callable Statement • Retrieving Metadata • Scrollable and Updatable ResultSet • Batch Processing
  • 3. Introduction Database System consists of : 1. A database 2. A software that stores and manages data in the database 3. Application programs that present the data and enable the user to interact with the database system. Application Programs Database Management System Database Application User System User Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 4. Relational Database System Based on Relational Data Model. Key Components are: 1. Structure 2. Integrity 3. Language Structure defines the representation of data. Integrity imposes constraints on data. Language provides means for accessing and manipulating the data. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 5. Relational Structure A Relation is a table consisting of non-duplicate rows. A Row of a table represents a Record, and called as a Tuple. A Column in a table represents an Attribute. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 6. Integrity Constraints An Integrity Constraint imposes a condition that all the legal values in a table must satisfy. Three types of Constraints are: 1. Domain Constraint 2. Primary Key Constraints 3. Foreign Key Constraints Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 7. Integrity Constraints Domain Constraints specify the permissible values for any attribute. Primary Key Constraint: Primary Key is a minimal Super key, used to identify a tuple in the database. Foreign Key Constraint: defines the relationship among relations (tables). A set of attributes F is a foreign key in any relation R that references relation T if: 1. The attributes in F have the same domain as the primary key in T. 2. A non-null value on F in R must match a primary key value in T. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 8. JDBC JDBC stands for Java DataBase Connectivity. JDBC is a standard Java API for database-independent connectivity between the Java programming language and a wide range of databases. By using JDBC, a Java application can access any kind of tabular data, especially data stored in a Relational Database. JDBC works with Java on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 9. JDBC • A JDBC based application is insulated from the characteristics of specific database engines. Java Application JDBC Access Database Oracle Database Sybase Database Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 10. Problem with Database Packages Different Vendors provided Database Packages with different APIs (functions defined for Application) in different Technologies. The Problem with native drivers was that a programmer has to learn a new API for each Database and application needs to be modified if database package is changed. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 11. Database Packages and Application Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 12. ODBC ODBC (Open DataBase Connectivity) provides the solution of that problem. It is a common API that is supported by all databases. ODBC represents function prototype in C. From Microsoft, 1994 Quite easy to use (preferred in .Net)… Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 13. ODBC Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 14. JDBC’s design is very similar to the design of ODBC. Database vendors provide JDBC drivers for the database package. JDBC helps in writing Java applications that manage these three programming activities: Connect to a data source, like a database Send queries and update statements to the database Retrieve and process the results received from the database in answer to our query JDBC Concepts Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 15. JDBC Concepts Driver Manager Loads database drivers, and manages the connection between the application and the driver Driver Translates API calls into operations for a specific data source Connection A session between an application and a database Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 16. JDBC Concepts Statement An SQL Statement to perform a query or update operation Metadata Information about returned data, the database and the driver ResultSet Logical set of columns and rows returned by executing an SQL statement (resulting tuples) Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 17. Steps during Execution The following steps are executed when running a JDBC application Import the necessary classes Load the JDBC driver Identify the database source Allocate a “connection” object (create) Allocate a “Statement” object (create) Execute a query using the “Statement” object Retrieve data from the returned “ResultSet” object Close the “ResultSet” object Close the “Statement” object Close the “Connection” object Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 18. JDBC Component Interaction Driver Manager Connection Statement ResultSet Driver Database Creates Creates Creates SQL Result (tuples) Establish Link to DB Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 19. Steps Involved in Basic JDBC Operations Driver Driver Manager Connection Statement Result Set 1. Load the JDBC driver class: Class.forName(“driverName”); 2. Open a database connection: DriverManager.getConnection (“jdbc:xxx:datasource”); 3. Issue SQL statements: stmt = con.createStatement(); stmt.executeQuery (“Select * from myTable”); 4. Process resultset: while (rs.next()) { name = rs.getString(“name”); amount = rs.getInt(“amt”); } Database Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 21. Two-Tier Database Access Model Java Application talks directly to the database. Accomplished through the JDBC driver which sends commands directly to the database. Results sent back directly to the application Application Space Java Application JDBC Driver Database SQL Command Result Set Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 22. Three-Tier Database Access Model JDBC driver sends commands to a middle tier, which in turn sends commands to database. Results are sent back to the middle tier, which communicates them back to the application Application Space Java Application JDBC Driver Database SQL Command Result Set Application Server (middle-tier) Proprietary Protocol Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 24. JDBC Driver Types JDBC-ODBC Bridge, plus ODBC driver (Type 1) JDBC methods -> Translate JDBC methods to ODBC methods -> ODBC to native methods -> Native methods API Native-API, partly Java driver (Type 2) JDBC methods -> Map JDBC methods to native methods (calls to vendor library) -> Native methods API (vendor library) JDBC-Network driver (Type 3) JDBC methods -> Translate to Native API methods through TCP/IP network -> Native API methods Pure Java driver (Type 4) Java methods -> Native methods in Java Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 25. Type 1: JDBC-ODBC Bridge This driver type is provided by Sun with JDK Provides JDBC access to databases through ODBC drivers ODBC driver must be configured for the bridge to work Only solution if no JDBC driver available for the DBMS Application Space Java Application JDBC – ODBC Bridge Database SQL Command Result Set ODBC Driver Proprietary Protocol Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 26. Type 2: Native-API, Partly Java Driver Native-API driver converts JDBC commands into DBMS- specific native calls Directly interfaces with the database Application Space Java Application Type 2 JDBC Driver Database SQL Command Result Set Native Database Library Proprietary Protocol Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 27. Type 3: JDBC-Network Driver Translates JDBC calls into a database-independent network protocol and sent to a middleware server. This server translates this DBMS- independent protocol into a DBMS- specific protocol and sent to the database. Results sent back to the middleware and routed to the client Application Space Java Application Type 3 JDBC Driver Database SQL Command Result Set Middleware Space Proprietary Protocol JDBC Driver Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 28. Type 4: Native-Protocol, Pure Java Driver Pure Java drivers that communicate directly with the vendor’s database JDBC commands converted to database engine’s native protocol directly Advantage: no additional translation or middleware layer Improves performance Application Space Java Application Type 4 JDBC Driver Database SQL Command Using Proprietary Protocol Result Set Using Proprietary Protocol Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 29. Driver Manager The DriverManager class is responsible for establishing connections to the data sources, accessed through the JDBC drivers. The driver can be loaded explicitly by calling the static method “forName” in the “Class” class and pass the driver argument Class.forName(“sun.jdbc.odbc.JdbcOdbcDriver”); The “forName()” method can throw a “ClassNotFoundException” if the driver class is not found. Hence, this function call should be in a try-catch block. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 30. Connection Object Connection object represents an established connection to a particular data source A connection object can also be used to query the data source (data and metadata) Different versions of getConnection() method contained in the DriverManager class that returns a connection object: Connection con = DriverManager.getConnection(source); Connection con = DriverManager.getConnection(source, u_name, pwd); Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 31. Statement Object Used for creating an SQL query, execute it, and retrieve the results. Statement objects are created by calling the createStatement() method of a valid connection object. Executes SQL query by calling the executeQuery() method. The SQL query string is passed as argument to the executeQuery() method The result of executing the query is returned as an object of type “ResultSet” Statement stmt = con.createStatement(); ResultSet myresults = stmt.executeQuery(“select * from authors”); Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 32. ResultSet Object The results of executing an SQL query are returned in the form of an object that implements the ResultSet interface. ResultSet object contains a “cursor” that points to a particular record (called the current record). When the ResultSet object is created, the cursor points to the position immediately preceding the first record. Several methods available to navigate the ResultSet by moving the cursor: first(), last(), beforeFirst(), afterLast(), next(), previous(), etc. //returns true if the move is successful isFirst() //whether you reached the beginning of the ResultSet isLast() // whether you reached the end of the ResultSet Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 33. Accessing Data in a ResultSet Methods for Retrieving Column Data: getString(), getInt(), getShort(), getFloat(), getDouble(), getTime() etc. We can always use getString() method for numerical values if we are not going to do some computations. Column names are NOT case sensitive. ResultSetMetaData object has metadata information about records, i.e., column names, data types etc. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 35. Statement Defines the methods and properties that enable us to send SQL or PL/SQL commands and receive data from database. Statement: Useful when we are using static SQL statements at runtime. -- The Statement interface cannot accept parameters. PreparedStatement: Used when we plan to use the SQL statements many times. -- The PreparedStatement interface accepts input parameters at runtime. CallableStatement: Used when we want to access database stored procedures. -- The CallableStatement interface can also accept runtime input parameters. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 36. Statement Methods boolean execute(String SQL): Returns a boolean value of true if a ResultSet object can be retrieved; otherwise, it returns false. -- Use this method to execute SQL DDL statements. 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. 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. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 37. PreparedStatement The PreparedStatement interface extends the Statement interface. PreparedStatement provides the facility of executing parameterized query. prepareStatement() method of Connection interface is used to create a prepared Statement. Statement pstmt = con.prepareStatement(“insert into Emp (id, name, age)” + “values (?, ?, ?)”); Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 38. It also provides methods for setting the parameters in the preparedStatement object. General method Signature: setXXX (int parameterIndex, X value) pstmt.setInt (1, 30) pstmt.setString (2, “Ravi Kant”) pstmt.setInt (3, 26) Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India) PreparedStatement Methods
  • 39. CallableStatement interface is used to execute SQL-stored procedures. A CallableStatement object can be created using the prepareCall (String call) method. CallableStatement cstmt = con.prepareCall (“{call sampleProcedure(?, ?, ?)}”); CallableStatement for a function: CallableStatement cstmt = con.prepareCall (“{? = call sampleProcedure(?, ?, ?)}”); Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India) CallableStatement
  • 40. create or replace procedure sampleProcedure (p1 in varchar, p2 out number, p3 in out integer) is begin -- do something end sampleProcedure; Parameters: PreparedStatement uses only IN parameter, while CallableStatement uses all three. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India) StoredProcedure
  • 41. Setting IN Parameter: setXXX (int parameterIndex, X value) cstmt.setInt (1, 30) cstmt.setString (2, “Ravi Kant”) Setting OUT Parameter: registerOutParameter (int parameterIndex, Types.XXX) -- Types.INTEGER, Types.DOUBLE etc cstmt.registerOutParameter (3, Types.INTEGER); Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India) CallableStatement Methods
  • 43. ResultSet A ResultSet object maintains a cursor pointing to its current row of data. Initially the cursor is positioned before the first row. The next method moves the cursor to the next row, and returns false when there are no more rows in the ResultSet object. A default ResultSet object is not updatable and has a cursor that moves forward only. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 44. Scrollable and Updateable Resultset With the new versions of JDBC, we can scroll the rows both forward and backward and move the cursor to a desired location using the first(), last(), next(), previous(), absolute(), or relative() method. We can insert, delete, or update a row in the result set and have the changes automatically reflected in the database. To obtain a scrollable or updatable result set, first create a statement with an appropriate type and concurrency mode. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 45. Scrollable and Updateable Resultset For static statement, Statement statement = connection.createStatement ( int resultSetType, int resultSetConcurrency); For a prepared statement, PreparedStatement statement = connection.prepareStatement( String sql, int resultSetType, int resultSetConcurrency); Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 46. Scrollable Resultset The possible values of resultSetType are the constants defined in the ResultSet: TYPE_FORWARD_ONLY: The result set is accessed forward sequentially. TYPE_SCROLL_INSENSITIVE: The result set is scrollable, but not sensitive to changes in the database. TYPE_SCROLL_SENSITIVE: The result set is scrollable and sensitive to changes made by others. Use this type if you want the result set to be scrollable and updatable. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 47. Updateable Resultset The possible values of resultSetConcurrency are the constants defined in the ResultSet: CONCUR_READ_ONLY: The result set cannot be used to update the database. CONCUR_UPDATABLE: The result set can be used to update the database. For example, scrollable and updatable resultset can be created as follows: Statement statement = connection.createStatement (ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE) Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 49. MetaData JDBC provides two interfaces for obtaining metadata. DatabaseMetaData interface for obtaining database information. ResultSetMetaData interface for obtaining information of specific ResultSet (e.g. column count and column names). getMetaData() method is used to obtain the metadata. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 50. DatabaseMetaData Following methods can be used to obtain database metadata: 1. getUserName() 2. getURL() 3. getDatabaseProductName() 4. getDatabaseProductVersion() 5. getDriverName() 6. getDriverVersion() 7. getDriverMajorVersion() 8. getDriverMinorVersion() 9. getMaxConnections() 10. getMaxTableNameLength() 11. getMaxColumnsInTable() Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 51. ResultSetMetaData It provides the following methods: 1. getColumnName(int) method to find the column names. 2. getColumnCount() method to find the number of columns in the resultset. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 53. Batch Processing Batch Processing allows to group related SQL statements into a batch and submit them with one call to the database. When we send several SQL statements to the database at once, it reduces the amount of communication overhead, thereby improving performance. DatabaseMetaData.supportsBatchUpdates() method is used to determine if the target database supports batch update processing. The method returns true if JDBC driver supports this feature. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 54. Methods for Batch Processing The addBatch() method is used to add individual statements to the batch. The executeBatch() is used to start the execution of all the statements grouped together. The executeBatch() returns an array of integers, and each element of the array represents the update count for the respective update statement. The clearBatch() method is used to remove all the statements added with the addBatch() method. We can not selectively choose which statement to remove. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 55. Steps to use Batch Processing Create a Statement object using createStatement() methods. Set auto-commit to false using setAutoCommit(). Add as many as SQL statements you like into batch using addBatch() method on created statement object. Execute all the SQL statements using executeBatch() method on created statement object. Finally, commit all the changes using commit() method. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 56. Example // Create statement object Statement stmt = conn.createStatement(); // Set auto-commit to false conn.setAutoCommit(false); // Create some SQL statements and add them in the batch String SQL = "INSERT INTO Emp (id, name, age) " + "VALUES(1,‘Ravi’, 25)"; stmt.addBatch(SQL); String SQL = "INSERT INTO Emp (id, name, age) " + "VALUES(200,'Raj', 30)"; stmt.addBatch(SQL); String SQL = "UPDATE Emp SET age = 35 " + "WHERE id = 100"; stmt.addBatch(SQL); // Create an int[] to hold returned values int[] count = stmt.executeBatch(); //Explicitly commit statements to apply changes conn.commit(); Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 57. 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 Driver Class Source Access sun.jdbc.odbc.JdbcOdbcDriver Already in JDK MySQL com.mysql.jdbc.Driver Website Oracle oracle.jdbc.driver.OracleDriver 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 Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 58. Developing JDBC Programs Loading drivers Establishing connections Creating and executing statements Processing ResultSet Connection connection = DriverManager.getConnection(databaseURL); Database URL Pattern Access jdbc:odbc:dataSource MySQL jdbc:mysql://hostname/dbname Oracle jdbc:oracle:thin:@hostname:port#:oracleDBSID Examples: For Access: 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"); Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 59. Developing JDBC Programs Loading drivers Establishing connections Creating and 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'"); Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 60. Developing JDBC Programs Loading drivers Establishing connections Creating and 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)); Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)
  • 61. JDBC connectivity with Oracle Oracle JDBC Thin Driver Format: jdbc:oracle:thin:@<host>:<port>:<SID> jdbc:oracle:thin:@//<host>:<port>/<service_name> Example: jdbc:oracle:thin:192.168.2.1:1521:X01A jdbc:oracle:thin:@//192.168.2.1:1521/XE The Oracle System ID (SID) is used to uniquely identify a particular database on a system. For this reason, one cannot have more than one database with the same SID on a computer system. Note: Support for SID is being phased out. Oracle recommends that users switch over to using service names. Ravi Kant Sahu, Asst. Professor @ Lovely Professional University, Punjab (India)