SlideShare une entreprise Scribd logo
1  sur  62
Télécharger pour lire hors ligne
By
Ravi Kant Sahu
Asst. Professor
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
 TranslatesAPI 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)
JDBCARCHITECTURE
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

Contenu connexe

Tendances

Java Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and ExampleJava Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and Examplekamal kotecha
 
Design patterns difference between interview questions
Design patterns   difference between interview questionsDesign patterns   difference between interview questions
Design patterns difference between interview questionsUmar Ali
 
Remote Method Invocation (RMI)
Remote Method Invocation (RMI)Remote Method Invocation (RMI)
Remote Method Invocation (RMI)Peter R. Egli
 
RMI Java Programming Lab Manual 2019
RMI Java Programming Lab Manual 2019RMI Java Programming Lab Manual 2019
RMI Java Programming Lab Manual 2019Gebreigziabher Ab
 
What is a Software Module?
What is a Software Module?What is a Software Module?
What is a Software Module?Syed Ali Raza
 
55 New Features in Java SE 8
55 New Features in Java SE 855 New Features in Java SE 8
55 New Features in Java SE 8Simon Ritter
 
Data management with ado
Data management with adoData management with ado
Data management with adoDinesh kumar
 
JDBC : Java Database Connectivity
JDBC : Java Database Connectivity JDBC : Java Database Connectivity
JDBC : Java Database Connectivity DevAdnani
 
Adbms 16 object definition language
Adbms 16 object definition languageAdbms 16 object definition language
Adbms 16 object definition languageVaibhav Khanna
 
Chapter-4 Enhanced ER Model
Chapter-4 Enhanced ER ModelChapter-4 Enhanced ER Model
Chapter-4 Enhanced ER ModelKunal Anand
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentationguest11106b
 
JDBC - JPA - Spring Data
JDBC - JPA - Spring DataJDBC - JPA - Spring Data
JDBC - JPA - Spring DataArturs Drozdovs
 
Need for Web Engineering
Need for Web EngineeringNeed for Web Engineering
Need for Web EngineeringNosheen Qamar
 

Tendances (20)

Asp.net file types
Asp.net file typesAsp.net file types
Asp.net file types
 
Java Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and ExampleJava Hibernate Programming with Architecture Diagram and Example
Java Hibernate Programming with Architecture Diagram and Example
 
Design patterns difference between interview questions
Design patterns   difference between interview questionsDesign patterns   difference between interview questions
Design patterns difference between interview questions
 
Remote Method Invocation (RMI)
Remote Method Invocation (RMI)Remote Method Invocation (RMI)
Remote Method Invocation (RMI)
 
Java beans
Java beansJava beans
Java beans
 
RMI Java Programming Lab Manual 2019
RMI Java Programming Lab Manual 2019RMI Java Programming Lab Manual 2019
RMI Java Programming Lab Manual 2019
 
What is a Software Module?
What is a Software Module?What is a Software Module?
What is a Software Module?
 
Grasp
GraspGrasp
Grasp
 
55 New Features in Java SE 8
55 New Features in Java SE 855 New Features in Java SE 8
55 New Features in Java SE 8
 
Dynamic web pages in java
Dynamic web pages in javaDynamic web pages in java
Dynamic web pages in java
 
Data management with ado
Data management with adoData management with ado
Data management with ado
 
JDBC : Java Database Connectivity
JDBC : Java Database Connectivity JDBC : Java Database Connectivity
JDBC : Java Database Connectivity
 
Adbms 16 object definition language
Adbms 16 object definition languageAdbms 16 object definition language
Adbms 16 object definition language
 
Unified Expression Language
Unified Expression LanguageUnified Expression Language
Unified Expression Language
 
Chapter-4 Enhanced ER Model
Chapter-4 Enhanced ER ModelChapter-4 Enhanced ER Model
Chapter-4 Enhanced ER Model
 
Jdbc Ppt
Jdbc PptJdbc Ppt
Jdbc Ppt
 
Conceptual Data Modeling
Conceptual Data ModelingConceptual Data Modeling
Conceptual Data Modeling
 
Hibernate Presentation
Hibernate  PresentationHibernate  Presentation
Hibernate Presentation
 
JDBC - JPA - Spring Data
JDBC - JPA - Spring DataJDBC - JPA - Spring Data
JDBC - JPA - Spring Data
 
Need for Web Engineering
Need for Web EngineeringNeed for Web Engineering
Need for Web Engineering
 

En vedette (16)

List classes
List classesList classes
List classes
 
Networking
NetworkingNetworking
Networking
 
Sms several papers
Sms several papersSms several papers
Sms several papers
 
Jun 2012(1)
Jun 2012(1)Jun 2012(1)
Jun 2012(1)
 
Event handling
Event handlingEvent handling
Event handling
 
Servlets
ServletsServlets
Servlets
 
Questions for Class I & II
Questions for Class I & IIQuestions for Class I & II
Questions for Class I & II
 
Multi threading
Multi threadingMulti threading
Multi threading
 
Distributed Programming (RMI)
Distributed Programming (RMI)Distributed Programming (RMI)
Distributed Programming (RMI)
 
Internationalization
InternationalizationInternationalization
Internationalization
 
Swing api
Swing apiSwing api
Swing api
 
Basic IO
Basic IOBasic IO
Basic IO
 
Packages
PackagesPackages
Packages
 
Collection framework
Collection frameworkCollection framework
Collection framework
 
Classes and Nested Classes in Java
Classes and Nested Classes in JavaClasses and Nested Classes in Java
Classes and Nested Classes in Java
 
Generics
GenericsGenerics
Generics
 

Similaire à Jdbc

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
 
Basic Java Database Connectivity(JDBC)
Basic Java Database Connectivity(JDBC)Basic Java Database Connectivity(JDBC)
Basic Java Database Connectivity(JDBC)suraj pandey
 
Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)Pooja Talreja
 
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
 
1. java database connectivity (jdbc)
1. java database connectivity (jdbc)1. java database connectivity (jdbc)
1. java database connectivity (jdbc)Fad Zulkifli
 
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
 
4-INTERDUCATION TO JDBC-2019.ppt
4-INTERDUCATION TO JDBC-2019.ppt4-INTERDUCATION TO JDBC-2019.ppt
4-INTERDUCATION TO JDBC-2019.pptNaveenKumar648465
 

Similaire à Jdbc (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
 
JDBC-Introduction
JDBC-IntroductionJDBC-Introduction
JDBC-Introduction
 
creating jdbc connection
creating jdbc connectioncreating jdbc connection
creating jdbc connection
 
creating jdbc connection
creating jdbc connectioncreating jdbc connection
creating jdbc connection
 
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
 
Jdbc introduction
Jdbc introductionJdbc introduction
Jdbc introduction
 
Basic Java Database Connectivity(JDBC)
Basic Java Database Connectivity(JDBC)Basic Java Database Connectivity(JDBC)
Basic Java Database Connectivity(JDBC)
 
3 jdbc
3 jdbc3 jdbc
3 jdbc
 
Rajesh jdbc
Rajesh   jdbcRajesh   jdbc
Rajesh jdbc
 
Assignment#10
Assignment#10Assignment#10
Assignment#10
 
Unit 5.pdf
Unit 5.pdfUnit 5.pdf
Unit 5.pdf
 
Java Database Connectivity (JDBC)
Java Database Connectivity (JDBC)Java Database Connectivity (JDBC)
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
 
1. java database connectivity (jdbc)
1. java database connectivity (jdbc)1. java database connectivity (jdbc)
1. java database connectivity (jdbc)
 
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
 
4-INTERDUCATION TO JDBC-2019.ppt
4-INTERDUCATION TO JDBC-2019.ppt4-INTERDUCATION TO JDBC-2019.ppt
4-INTERDUCATION TO JDBC-2019.ppt
 

Plus de Ravi_Kant_Sahu

Plus de Ravi_Kant_Sahu (16)

Common Programming Errors by Beginners in Java
Common Programming Errors by Beginners in JavaCommon Programming Errors by Beginners in Java
Common Programming Errors by Beginners in Java
 
Gui programming (awt)
Gui programming (awt)Gui programming (awt)
Gui programming (awt)
 
Event handling
Event handlingEvent handling
Event handling
 
String handling(string buffer class)
String handling(string buffer class)String handling(string buffer class)
String handling(string buffer class)
 
String handling(string class)
String handling(string class)String handling(string class)
String handling(string class)
 
Packages
PackagesPackages
Packages
 
Array
ArrayArray
Array
 
Keywords and classes
Keywords and classesKeywords and classes
Keywords and classes
 
Wrapper classes
Wrapper classesWrapper classes
Wrapper classes
 
Methods and constructors
Methods and constructorsMethods and constructors
Methods and constructors
 
Java keywords
Java keywordsJava keywords
Java keywords
 
Inheritance
InheritanceInheritance
Inheritance
 
Operators in java
Operators in javaOperators in java
Operators in java
 
Control structures in Java
Control structures in JavaControl structures in Java
Control structures in Java
 
Genesis and Overview of Java
Genesis and Overview of Java Genesis and Overview of Java
Genesis and Overview of Java
 
L2 datatypes and variables
L2 datatypes and variablesL2 datatypes and variables
L2 datatypes and variables
 

Dernier

Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 

Dernier (20)

Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 

Jdbc

  • 1. By Ravi Kant Sahu Asst. Professor 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  TranslatesAPI 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)