0% found this document useful (0 votes)
16 views

database

JDBC (Java Database Connectivity) is an API that enables Java applications to interact with various database management systems using a standard interface. It includes components such as the JDBC API, Driver Manager, Test Suite, and JDBC-ODBC Bridge, allowing developers to connect to databases, execute SQL statements, and manage results. The document outlines the architecture, benefits, and basic steps for using JDBC, including driver registration, connection establishment, statement creation, and executing SQL commands.

Uploaded by

Dhruv Jaradi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

database

JDBC (Java Database Connectivity) is an API that enables Java applications to interact with various database management systems using a standard interface. It includes components such as the JDBC API, Driver Manager, Test Suite, and JDBC-ODBC Bridge, allowing developers to connect to databases, execute SQL statements, and manage results. The document outlines the architecture, benefits, and basic steps for using JDBC, including driver registration, connection establishment, statement creation, and executing SQL commands.

Uploaded by

Dhruv Jaradi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 148

Chapter 1: JDBC Programming

Prof Hetal Gaudani


Department of Computer Engineering
G H Patel College of Engineering & Technology
What is JDBC?
• JDBC stands for Java Database Connectivity.
• JDBC is Java application programming interface(API) that allows
the Java programmers to access database management system
from Java code.
• JDBC provides methods for querying and updating the data in
Relational Database Management system such as SQL, Oracle
etc
• It is a part of JavaSE (Java Standard Edition).
• JDBC API uses JDBC drivers to connect with the database.
• It was developed by JavaSoft, a subsidiary of Sun
Microsystems.
• JDBC API uses JDBC drivers to connect with the database
• The classes and interfaces of JDBC allow the application to send
requests made by users to the specified database.
JDBC
• JDBC 1.0 API, which provides the basic functionality for data access.
• The JDBC 2.0 API supplements the basic API with more advanced
features and provides a standard way to access the latest object-
relational features being supported by today's relational database
management systems.
• In addition, the new API includes features such as scrollable and
updatable result sets and improved performance.
• It also extends JDBC technology beyond the client to the server with
connection pooling and distributed transactions.
• JDBC 2.0 API-the complete JDBC API, including both the java.sql
package (the JDBC 2.0 core API) and the javax.sql package (the JDBC
Standard Extension API). The J2EE, includes the complete JDBC 2.0
API.
JDBC
• Using JDBC we can do the following (and more):

- Connect to a database

- Execute SQL statements to query the database

- Generate query results

- Perform updates, inserts and deletions

- Execute Stored Procedures

-
JDBC Benefits

• Developer only writes one API for access any


database

• No need to rewrite code for different databases

• No need to know the database vendor specific APIs

• It provides a standard API and is vendor independent

• Virtually every database has some sort of JDBC


driver

• JDBC is part of the standard J2SE platform


JDBC Architecture

• Drivers written either in Java (used on any platform/applets) or


using native methods, tied to the underlying platform
database driver
• A database driver in JDBC (Java Database
Connectivity) is a software component that
enables a Java application to interact with a
specific database management system
(DBMS).
• The driver translates the Java code into
database-specific calls and handles the
communication between the Java application
and the database server.
JDBC includes four components:
• The JDBC API —
• JDBC Driver Manager —
• JDBC Test Suite —
• JDBC-ODBC Bridge —
JDBC API
1. The JDBC application programming interface provides the facility
for accessing the relational database from the Java
programming language.
2. The API technology provides the industrial standard for
independently connecting Java programming language and a
wide range of databases.
3. Using the JDBC API, applications can execute SQL statements,
retrieve results, and propagate changes back to an underlying
data source.
• The JDBC API can also interact with multiple data sources in a
distributed, heterogeneous environment.

• The JDBC API has four main interface.


• The latest version of JDBC 4.0 application programming interface
is divided into two packages
i) java.sql
JDBC Driver Manager
1. The JDBC DriverManager class defines objects which can connect Java
applications to a JDBC driver.

2. DriverManager has traditionally been the backbone of the JDBC


architecture.

3. It's very simple and small that is used to provide a means of managing the
different types of JDBC database driver running on an application.

4. The main responsibility of JDBC database driver is to load all the drivers
found in the system properly as well as to select the most appropriate
driver from opening a connection to a database. The Driver Manager also
helps to select the most appropriate driver from the previously loaded
drivers when a new open database is connected.
JDBC Test Suite
• The JDBC driver test suite helps you to determine that
JDBC drivers will run your program.
• It ensures that the driver behaves correctly and
supports the required features and functionality of
the JDBC API.
• The JDBC Test Suite is essential for developers and
database vendors to validate the compatibility and
reliability of their JDBC drivers.
• It is used to test the operation(such as insertion,
deletion, updation) being performed by JDBC Drivers.
JDBC-ODBC Bridge
• The Java Software bridge provides JDBC access
via ODBC drivers.
• Note that you need to load ODBC binary code
onto each client machine that uses this driver.
• This driver translates JDBC method calls into
ODBC function calls.
• The Bridge implements Jdbc for any database for
which an Odbc driver is available.
• The Bridge is always implemented as the
sun.jdbc.odbc Java package and it contains a
native library used to access ODBC.
Basic steps to use a database in Java
1.Establish a connection (
Register Driver class and
create connection)
2.Create JDBC Statements
3.Execute SQL Statements
4.GET ResultSet
5.Close connections
Understanding basic JDBC steps
• Obtaining connection
• Creating JDBC statement
• Executing SQL statement
• Closing connection
• In JDBC (Java Database Connectivity), the
DriverManager class is a crucial part of the
API.
• It manages a
– list of database drivers
– handles establishing a connection to a database
by selecting an appropriate driver from the list of
registered drivers.
Obtaining connection

1) Register Driver object with DriverManager


2) Establish connection using DriverManager
1. Register Driver object with
DriverManager
Three approaches to register Driver with
DriverManager

A. DriverManager.registerDriver(Driverinstance)
ex:
DriverManager.registerDriver(new
sun.jdbc.odbc.JdbcOdbcDriver());
B. Class.forName(Driver_class_name);
Class.forName(sun.jdbc.odbc.JbcOdbcDriver);

C. System.setProperty(“jdbc.driver”,”
sun.jdbc.odbc.JbcOdbcDriver”);
OR
Java -Djava.drivers=sun.jdbc.odbc.JbcOdbcDriver
myProg
Establish a connection
1. Load driver
import java.sql.*;
1. Load the vendor specific driver
• Load the JDBC Driver: driver must be in the CLASSPATH environment
variable and/or within the application server/containers relevant libraries.
A class is loaded into the JVM for use later, when we want to open a
connection.

Syntax of forName() method

• public static void forName(String className) throws

ClassNotFoundException
• Class.forName("com.mysql.jdbc.Drive");
When the driver is loaded into memory, it registers itself with the
java.sql.DriverManager classes as an available database driver.
MySQL
● Driver Class: com.mysql.cj.jdbc.Driver
● JAR File: mysql-connector-java-x.x.x.jar

old driver: com.mysql.jdbc.Driver

PostgreSQL
● Driver Class: org.postgresql.Driver
● JAR File: postgresql-x.x.x.jar

Oracle
● Driver Class: oracle.jdbc.driver.OracleDriver
● JAR File: ojdbc8.jar (for Java 8 and higher)

Microsoft SQL Server


● Driver Class: com.microsoft.sqlserver.jdbc.SQLServerDriver
● JAR File: mssql-jdbc-x.x.x.jre8.jar (for Java 8)

IBM DB2
● Driver Class: com.ibm.db2.jcc.DB2Driver
● JAR File: db2jcc4.jar
SQLite

● Driver Class: org.sqlite.JDBC


● JAR File: sqlite-jdbc-x.x.x.jar

MariaDB

● Driver Class: org.mariadb.jdbc.Driver


● JAR File: mariadb-java-client-x.x.x.jar

Sybase (SAP ASE)

● Driver Class: com.sybase.jdbc4.jdbc.SybDriver


● JAR File: jconn4.jar

H2 Database

● Driver Class: org.h2.Driver


● JAR File: h2-x.x.x.jar

Apache Derby

● Driver Class: org.apache.derby.jdbc.EmbeddedDriver


● JAR File: derby-x.x.x.jar

Informix

● Driver Class: com.informix.jdbc.IfxDriver


● JAR File: ifxjdbc.jar

Teradata

● Driver Class: com.teradata.jdbc.TeraDriver


● JAR File: terajdbc4.jar
javac -classpath mysql-connector.jar;. data.java
2. create Connection
• 2. Make the connection
The getConnection() method of DriverManager class is
used to establish connection with the database.

Syntax of getConnection() method

1) public static Connection getConnection(String


url)throws SQLException

2) public static Connection getConnection(String


url,String name,String password)
throws SQLException
• URL is as Follow
Jdbc:<sub Protocol>:info
Sub protocol-> vendor specific name of driver
Info-> additional information required to to
establish connection like database name,port
number(ipaddress:port/databasename)

– Connection con =
DriverManager.getConnection(
"jdbc:mysql://10.10.13.202:3306/test", username,
passwd);
3. Create JDBC Statements

❖The createStatement() method of


Connection interface is used to create
statement.
❖The object of statement is responsible to
execute queries with the database.
Syntax of createStatement() method
public Statement createStatement()throws
SQLException

Statement stmt = con.createStatement() ;


4. Executing SQL Statements

• The executeQuery() method of Statement interface


is used to execute queries to the database.
• This method returns the object of ResultSet that can
be used to get all the records of a table.
Syntax of executeQuery() method
• public ResultSet executeQuery(String sql)throws
SQLException
String queryLehigh = "select * from student";
ResultSet rs =Stmt.executeQuery(queryLehigh);
• Get ResultSet
while (rs.next()) {
int ssn = rs.getInt("SSN");
String name = rs.getString("NAME");
int marks = rs.getInt("MARKS"); }
5. Close the connection object

❖By closing connection object statement and


ResultSet will be closed automatically.
❖ The close() method of Connection interface
is used to close the connection.
Syntax of close() method
public void close()throws SQLException
Example to close connection
con.close();
Example
1. import java.sql.*;
2. class MysqlCon{
3. public static void main(String args[]){
4. try{
5. Class.forName("com.mysql.jdbc.Driver");
6. Connection con=DriverManager.getConnection(
7. "jdbc:mysql://10.10.13.202:3306/test","root","root");
8. //here sonoo is database name, root is username and password
9. Statement stmt=con.createStatement();

10. ResultSet rs=stmt.executeQuery("select * from tbl_datatable");


11. while(rs.next())
12. System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3)+ “ “
+rs.getString(“mobile”));
13. con.close();
14. }catch(Exception e){ System.out.println(e);}
15. }
16. }
The statement interface is used to create SQL basic statements in
Java it provides methods to execute queries with the database.
There are different types of statements that are used in JDBC as
follows:
Three kinds of Statements

Statement
Prepared Statement
Callable Statement
Statement
• Use for general-purpose access to your database.
• Useful when you are using static SQL statements at
runtime.
• The Statement interface cannot accept parameters.
• Statement is simple SQL statement and takes no
parameters, execute and compile every time when
request is generated to database server.
• You obtain a JDBC Statement from a JDBC Connection.
Once you have a Java Statement instance you can
execute either a database query or an database
update with it
Creating Statement Object:

• Before you can use a Statement object to


execute a SQL statement, you need to create
one using the Connection object's
createStatement( ) method, as in the following
example:
Statement stmt = null;
try {
stmt = conn.createStatement( );
..}
catch (SQLException e) { . . . }
finally { . . . }
Commonly used methods of Statement interface:
The important methods of Statement interface are as follows:

1) public ResultSet executeQuery(String sql): is used to execute


SELECT query. It returns the object of ResultSet.
2) public int executeUpdate(String sql): is used to execute specified
query, it may be create, drop, insert, update, delete etc.
3) public boolean execute(String sql): is used to execute queries
that may return multiple results.
4) public int[] executeBatch(): is used to execute batch of
commands.
Executing a Query via a Statement
String sql = "select * from people";

ResultSet result = statement.executeQuery(sql);

while(result.next()) {

String name = result.getString("name");


long age = result.getLong ("age");

}
Execute an Update via a Statement
Statement statement = connection.createStatement();

String sql = "update people set name='John' where


id=123";

int rowsAffected = statement.executeUpdate(sql);


1. import java.sql.*;
2. class FetchRecord{
3. public static void main(String args[])throws Exception{
4. Class.forName("oracle.jdbc.driver.OracleDriver");
5. Connection
con=DriverManager.getConnection("jdbc:mysql://10.10.13.202:3306/test","system","orac
le");
6. Statement stmt=con.createStatement();

7. int resultI=stmt.executeUpdate("insert into emp765 values(33,'Irfan',50000)");


8. System.out.println(resultI+" records Inserted");
9. int resultU=stmt.executeUpdate("update emp765 set name='Vimal',salary=10000
where id=33");
10. System.out.println(resultU+" records Updated");
11.int resultD=stmt.executeUpdate("delete from emp765 where id=33");
12.System.out.println(resultD+" records affected");
13. con.close();
14. }
15. }
DriverManager class
• The DriverManager class is the component of JDBC API and
also a member of the java.sql package.
• The DriverManager class acts as an interface between
users and drivers.
• It keeps track of the drivers that are available and handles
establishing a connection between a database and the
appropriate driver.
• It contains all the appropriate methods to register and
deregister the database driver class and to create a
connection between a Java application and the database.
• The DriverManager class maintains a list of Driver classes
that have registered themselves by calling the method
DriverManager.registerDriver().
Note that before interacting with a Database, it is a mandatory process to register the
driver; otherwise, an exception is thrown
Method

1) public static synchronized void registerDriver(Driver driver):


is used to register the given driver with DriverManager. No action is performed
by the method when the given driver is already registered.
2) public static synchronized void deregisterDriver(Driver driver):
is used to deregister the given driver (drop the driver from the list) with
DriverManager. If the given driver has been removed from the list, then no
action is performed by the method.
3) public static Connection getConnection(String url) throws
SQLException:
is used to establish the connection with the specified url. The SQLException is
thrown when the corresponding Driver class of the given database is not
registered with the DriverManager.
4) public static Connection getConnection(String url,String
userName,String password) throws SQLException:
is used to establish the connection with the specified url, username, and
password. The SQLException is thrown when the corresponding Driver class of
5) public static Driver getDriver(String url)
Those drivers that understand the mentioned URL (present in the parameter
of the method) are returned by this method provided those drivers are
mentioned in the list of registered drivers.
6) pubic static int getLoginTimeout()
The duration of time a driver is allowed to wait in order to establish a
connection with the database is returned by this method.
7) pubic static void setLoginTimeout(int sec)
The method provides the time in seconds. sec mentioned in the parameter
is the maximum time that a driver is allowed to wait in order to establish a
connection with the database. If 0 is passed in the parameter of this
method, the driver will have to wait infinitely while trying to establish the
connection with the database.
Connection interface
A Connection is a session between a Java application and a database. It helps to establish a connection
with the database.

The Connection interface is a factory of Statement, PreparedStatement, and DatabaseMetaData, i.e., an


object of Connection can be used to get the object of Statement and DatabaseMetaData. The
Connection interface provide many methods for transaction management like commit(), rollback(),
setAutoCommit(), setTransactionIsolation(), etc.
Commonly used methods of Connection
interface:
1) public Statement createStatement(): creates a statement object that can be used to
execute SQL queries.
2) public Statement createStatement(int resultSetType,int resultSetConcurrency):
Creates a Statement object that will generate ResultSet objects with the given type and
concurrency.
3) public void setAutoCommit(boolean status): is used to set the commit status. By
default, it is true.
4) public void commit(): saves the changes made since the previous commit/rollback is
permanent.
5) public void rollback(): Drops all changes made since the previous commit/rollback.
6) public void close(): closes the connection and Releases a JDBC resources immediately.
7) PreparedStatement prepareStatement(String sql):Creates a PreparedStatement
object for sending parameterized SQL statements to the database.

8) CallableStatement prepareCall(String sql) :Creates a CallableStatement object for


calling database stored procedures.

9)DatabaseMetaData getMetaData(): Retrieves a DatabaseMetaData object that contains


metadata about the database to which this Connection object represents a connection.
Key Methods of the Connection Interface
Creating Statements
1. createStatement():

Statement stmt = conn.createStatement();


● Creates a Statement object for sending SQL statements to the database.

1. prepareStatement(String sql):

PreparedStatement pstmt = conn.prepareStatement("SELECT * FROM mytable


WHERE column1 = ?");

● Creates a PreparedStatement object for sending parameterized SQL statements to the


database.

1. prepareCall(String sql):
CallableStatement cstmt = conn.prepareCall("{call myStoredProc(?, ?)}");
● Creates a CallableStatement object for calling stored procedures.
Prepared Statement
• derived from Statement
• If you want to execute a Statement object many times, it usually
reduces execution time.
• PreparedStatement is precompiled SQL statement and reside in
PreparedStatement object.
• This PreparedStatement object executes multiple times SQL
statement without compiling it again and again.
• This is kind of caching SQL statement and execute on parameters
specification. First time when it executes, it runs slow but after
that it runs much faster than simple Statement Object.
• Sometimes it is called dynamic statement because it takes
parameter setter option.
• A SQL statement is given inside when PreparedStatement is
creating.
• PreparedStatement is in java.sql.PreparedStatement
How to get the instance of
PreparedStatement?
The prepareStatement() method of Connection interface is used to
return the object of PreparedStatement. Syntax:

1. public PreparedStatement prepareStatement(String query)throws


SQLException
1. import java.sql.*;
2. class InsertPrepared{
3. public static void main(String args[]){
4. try{
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6.
7. Connection
con=DriverManager.getConnection("jdbc:mysql://10.10.13.202:3306/test","root"," ");
8.
9. PreparedStatement stmt=con.prepareStatement("insert into Emp values(?,?)");
10. stmt.setInt(1,101);//1 specifies the first parameter in the query
11. stmt.setString(2,"Ratan");
12.
13. int i=stmt.executeUpdate();
14. System.out.println(i+" records inserted");
15.
16. con.close();
17.
18. }catch(Exception e){ System.out.println(e);}
19.
20. }
21. }
Example of PreparedStatement
interface that updates the record

1. PreparedStatement stmt=con.prepareStatement("update emp set


name=? where id=?");

2. stmt.setString(1,"Sonoo");//1 specifies the first parameter in the


query i.e. name
3. stmt.setInt(2,101);

4. int i=stmt.executeUpdate();

5. System.out.println(i+" records updated");


Example of PreparedStatement
interface that deletes the record

1. PreparedStatement stmt=con.prepareStatement("delete from


emp where id=?");

2. stmt.setInt(1,101);

3. int i=stmt.executeUpdate();

4. System.out.println(i+" records deleted");


Example of PreparedStatement
interface that retrieve the records
of a table
1. PreparedStatement stmt=con.prepareStatement("select * from
emp");

2. ResultSet rs=stmt.executeQuery();

3. while(rs.next()){

4. System.out.println(rs.getInt(1)+" "+rs.getString(2));

5. }
Example of PreparedStatement to
insert records until user press n
import java.sql.*;
import java.io.*;
class RS{
public static void main(String args[])throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localho
st:1521:xe","system","oracle");
PreparedStatement ps=con.prepareStatement("insert into
emp130 values(?,?,?)");
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
do{
System.out.println("enter id:"); int id=Integer.parseInt(br.readLine());
System.out.println("enter name:"); String name=br.readLine();
System.out.println("enter salary:"); float salary=Float.parseFloat(br.readLine());

ps.setInt(1,id);
ps.setString(2,name);
ps.setFloat(3,salary);
int i=ps.executeUpdate();
System.out.println(i+" records affected");

System.out.println("Do you want to continue: y/n");


String s=br.readLine();
if(s.startsWith("n")){
break;
}
}while(true);
con.close();
}}
Java CallableStatement Interface
This will cover be covered later on
ResultSet
The Java JDBC ResultSet interface represents the
result of a database query.
• 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 preceeding 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
JDBC 2.0 Navigation Methods for
Scrollable Result Sets
boolean next ( ) Advances the cursor to the next row.
boolean previous ( ) Moves the cursor back one row.
boolean first ( ) Moves the cursor to the first row.
boolean last ( ) Moves the cursor to the last row.
void beforeFirst ( ) Moves the cursor before the first
row, usually in anticipation of
calling next ( )
void afterLast ( ) Moves the cursor after the last row,
usually in anticipation of
calling previous ( )
boolean Moves the cursor to the specified
absolute (int row) row. Specifying a negative number
moves the cursor relative to the
end of the result set;
JDBC 2.0 Navigation Methods for Scrollable
Result Sets (contd.)
boolean Moves the cursor forward or
relative (int row) backward the number of rows
specified.
boolean True if the cursor is before the
isBeforeFirst ( ) first row.
boolean True if the cursor is after the
isAfterLast ( ) last row.
boolean isFirst ( ) True if the cursor is positioned on
the first row.
boolean isLast ( ) True if the cursor is positioned on
the last row.
Accessing Data in a ResultSet
• We can retrieve the value of any column for the current row (specified
by the cursor) by name or position
– Using Name: authorNames.getString(“lastname”);
– Using Position: authorNames.getString(2);

– Using the column position is a little bit faster


• 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.
Iterating the ResultSet
• To iterate the ResultSet you use its next() method.
• The next() method returns true if the ResultSet has a next record, and moves
the ResultSet to point to the next record.
• If there were no more records, next() returns false, and you can no longer.
Once the next() method has returned false, you should not call it anymore.
Doing so may result in an exception.
while(result.next()) {
// ... get column values from this record
}

• next() method is actually called before the first record is accessed. That means,
that the ResultSet starts out pointing before the first record.
• Once next() has been called once, it points at the first record.
Accessing Column Values
When iterating the ResultSet you want to access the column values of each record. You
do so by calling one or more of the many getXXX() methods. You pass the name of the
column to get the value of, to the many getXXX() methods. For instance:
while(result.next()) {

result.getString ("name");
result.getInt ("age");
result.getBigDecimal("coefficient");

// etc.
}

There are a lot of getXXX() methods you can call, which return the value of the column
as a certain data type, e.g. String, int, long, double, BigDecimal etc. They all take the
name of the column to obtain the column value for, as parameter.
result.getArray("columnName"); result.getInt("columnName");
result.getAsciiStream("columnName"); result.getLong("columnName");
result.getBigDecimal("columnName"); result.getNCharacterStream("columnNa
result.getBinaryStream("columnName"); me");
result.getBlob("columnName"); result.getObject("columnName");
result.getBoolean("columnName"); result.getRef("columnName");
result.getBlob("columnName"); result.getRowId("columnName");
result.getShort("columnName");
result.getBoolean("columnName");
result.getSQLXML("columnName");
result.getByte("columnName");
result.getString("columnName");
result.getBytes("columnName");
result.getTime("columnName");
result.getCharacterStream("columnNam
result.getTimestamp("columnName");
e");
result.getUnicodeStream("columnName")
result.getClob("columnName");
;
result.getDate("columnName"); result.getURL("columnName");
result.getDouble("columnName");
result.getFloat("columnName");
The getXXX() methods also come in versions that take a column index instead of a
column name. For instance:
while(result.next()) {

result.getString (1);
result.getInt (2);
result.getBigDecimal(3);

// etc.
}

The index of a column typically depends on the index of the column in the SQL
statement. For instance, the SQL statement
select name, age, coefficient from person

has three columns. The column name is listed first, and will thus have index 1 in the
ResultSet. The column age will have index 2, and the column coefficient will have index
3.
Sometimes you do not know the index of a certain column ahead of time. For
instance, if you use a select * from type of SQL query, you do not know the
sequence of the columns.

If you do not know the index of a certain column you can find the index of that
column using the ResultSet.findColumn(String columnName) method, like
this:
int nameIndex = result.findColumn("name");
int ageIndex = result.findColumn("age");
int coeffIndex = result.findColumn("coefficient");

while(result.next()) {
String name = result.getString (nameIndex);
int age = result.getInt (ageIndex);
BigDecimal coefficient = result.getBigDecimal (coeffIndex);
}
ResultSet Type, Concurrency and
Holdability
When you create a ResultSet there are three attributes you can set. These are:

1. Type
2. Concurrency
3. Holdability

You set these already when you create the Statement or PreparedStatement
Statement statement = connection.createStatement(
ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY,
ResultSet.CLOSE_CURSORS_OVER_COMMIT
);

PreparedStatement statement =
connection.prepareStatement(sql,
ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_READ_ONLY,
ResultSet.CLOSE_CURSORS_OVER_COMMIT
);
What are different types of resultset
in JDBC?
• Forward-only
As name suggest, this type can only move forward and
are non-scrollable.
• Scroll-insensitive
This type is scrollable which means the cursor can
move in any direction. It is insensitive which means
any change to the database will not show change in
the resultset while it open.
• Scroll-sensitive
This type allows cursor to move in any direction and
also propagates the changes done to the database
Scrollable Result Sets
• In JDBC1.0, result sets could be navigated in
only one direction (forward) and starting at
only one point (first row)
• Since JDBC 2.0, the cursor can be
manipulated as if it were a array index
• Methods exist for reading both forward and
backward, for starting from any row, and
for testing the current cursor location.
Creating Scrollable Result Sets
• Statement object created with parameters to indicate
specific capabilities
• Connection.createStatement() method can have up to
three parameters:
– resultSetType – type of scrolling to be used
– resultSetConcurrency – indicates whether the result set can be
updated
– resultSetHoldability – specifies whether to close cursors when a
commit is done
• Example
– stmt = con.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
Constants in Result Sets
• Cursor Related Constants
– TYPE_FORWARD_ONLY
• JDBC 1.0-style navigation in which the cursor starts
at the first row and can only move forward.
– TYPE_SCROLL_INSENSITIVE
• All cursor positioning methods are enabled; the
result set doesn’t reflect changes made by others in
the underlying table.
– TYPE_SCROLL_SENSITIVE
• All cursor positioning methods are enabled the
result set reflects changes made by others in the
underlying table.
Constants in Result Sets (contd.)
• Updating Record Sets
– CONCUR_READ_ONLY
• The results set won’t be updatable
– CONCUR_UPDATABLE
• Rows can be added and deleted, and columns can
be updated.
• Closing Cursors
– HOLD_CURSORS_OVER_COMMIT
• Do not close cursors after a commit is done.
– CLOSE_COURSORS_AT_COMMIT
• Close cursors when a commit is done.
callable statement
A stored procedure is a group of SQL statements
that form a logical unit and perform a particular
task, and they are used to encapsulate a set of
operations or queries to execute on a database
server
Stored procedures can be compiled and
executed with different parameters and results,
and they can have any combination of input,
output, and input/output parameters.
Create a Procedure in Database
The procedure is created in the database using
the CREATE PROCEDURE statement
For the sake of demonstration, we will create a new stored
procedure named get_candidate_skill that accepts
candidate_id as the IN parameter and returns a result set that
contains the skills of the candidate
DELIMITER $$
CREATE PROCEDURE get_candidate_skill(IN candidate_id INT)
BEGIN
SELECT candidates.id, first_name,last_name,
skills.name AS skill
FROM candidates
INNER JOIN candidate_skills ON candidates.id =
candidate_skills.candidate_id
INNER JOIN skills ON skills.id = candidate_skills.skill_id
WHERE candidates.id = candidate_id;
END$$
DELIMITER ;
Let’s call this stored procedure for candidate id
with value 122.

CALL get_candidate_skill(122);
To call stored procedures or stored functions in MySQL
from JDBC, you use CallableStatement object, which
inherits from PreparedStatement object.
The general syntax of calling a stored procedure is as
follows:
{?= call procedure_name(param1,param2,...)}
• You wrap the stored procedure call within braces ({}).
• If the stored procedure returns a value, you need to
add the question mark and equal (?=) before the call
keyword.
• If a stored procedure does not return any values, you
just omit the ?= sign.
• In case the stored procedure accepts any parameters,
you list them within the opening and closing
parentheses after the stored procedure’s name.
The following are examples of using the syntax for
calling stored procedures in different contexts:

Syntax Stores Procedures


{ call procedure_name() } Accept no parameters
and return no value
{ call procedure_name(?,?) } Accept two
parameters and return no value
{?= call procedure_name() }Accept no parameter
and return value
{?= call procedure_name(?) } Accept one
parameter and return value
In MySQL, a parameter has one of three modes: IN,OUT,
or INOUT.

IN parameters
IN is the default mode.
When you define an IN parameter in a stored procedure,
the calling program has to pass an argument to the stored
procedure. In addition, the value of an IN parameter is
protected.
It means that even the value of the IN parameter is
changed inside the stored procedure, its original value is
retained after the stored procedure ends. In other words,
the stored procedure only works on the copy of the IN
parameter.
OUT parameters
The value of an OUT parameter can be changed
inside the stored procedure and its new value is
passed back to the calling program. Notice that the
stored procedure cannot access the initial value of
the OUT parameter when it starts.

INOUT parameters
An INOUT parameter is a combination of IN and OUT
parameters. It means that the calling program may
pass the argument, and the stored procedure can
modify the INOUT parameter, and pass the new value
back to the calling program.
Defining a parameter
Here is the basic syntax of defining a parameter
in stored procedures:

[IN | OUT | INOUT] parameter_name


datatype[(length)]
DELIMITER //

CREATE PROCEDURE GetOfficeByCountry(


IN countryName VARCHAR(255)
)
BEGIN
SELECT *
FROM offices
WHERE country = countryName;
END //

DELIMITER ;

CALL GetOfficeByCountry('USA');
CALL GetOfficeByCountry('France')
DELIMITER $$

CREATE PROCEDURE GetOrderCountByStatus (


IN orderStatus VARCHAR(25),
OUT total INT
)
BEGIN
SELECT COUNT(orderNumber)
INTO total
FROM orders
WHERE status = orderStatus;
END$$

DELIMITER ;
To find the number of orders that already shipped, you
call GetOrderCountByStatus and pass the order status as
of Shipped, and also pass a session variable ( @total ) to
receive the return value.

CALL GetOrderCountByStatus('Shipped',@total);
SELECT @total;
To get the number of orders that are in-process, you call
the stored procedure GetOrderCountByStatus as follows:

CALL GetOrderCountByStatus('in process',@total);


SELECT @total AS total_in_process;
DELIMITER $$

CREATE PROCEDURE SetCounter(


INOUT counter INT,
IN inc INT
)
BEGIN
SET counter = counter + inc;
END$$

DELIMITER ;

These statements illustrate how to call the SetSounter stored procedure:

SET @counter = 1;
CALL SetCounter(@counter,1); -- 2
CALL SetCounter(@counter,1); -- 3
CALL SetCounter(@counter,5); -- 8
SELECT @counter; -- 8
CREATE PROCEDURE `summary_report`(
IN title VARCHAR(45),OUT totalBooks INT,
OUT totalValue DOUBLE, INOUT highPrice DOUBLE
)
BEGIN
DECLARE maxPrice DOUBLE;
SELECT COUNT(*) AS bookCount, SUM(price) as total
FROM book b JOIN author a ON b.author_id = a.author_id
AND b.title LIKE CONCAT('%', title, '%')
INTO totalBooks, totalValue;
SELECT MAX(price) FROM book WHERE price INTO
maxPrice;
IF (maxPrice > highPrice) THEN
SET highPrice = maxPrice;
END IF;
END
To retrieve the values of the OUT and INOUT
parameters, JDBC requires these parameters
must be registered before calling the procedure,
by invoking the following method on
CallableStatementobject:
void registerOutParameter(int parameterIndex,
int sqlType)
CallableStatement statement = conn.prepareCall("{call
summary_report(?, ?, ?, ?)}");

statement.registerOutParameter(2, Types.INTEGER);
statement.registerOutParameter(3, Types.DOUBLE);
statement.registerOutParameter(4, Types.DOUBLE);

statement.setString(1, "Java");
statement.setDouble(4, 50);
statement.execute();
Integer totalBook = (Integer) statement.getObject(2,
Integer.class);
Double totalValue = statement.getDouble(3);
Double highPrice = statement.getDouble("highPrice");
public class StoredProcedureCallExample2 {
public static void main(String[] args) {
String dbURL = "jdbc:mysql://localhost:3306/booksdb";
String user = "root";
String password = "P@ssw0rd";
try {
Connection conn =
DriverManager.getConnection(dbURL, user, password);
CallableStatement statement = conn.prepareCall("{call
summary_report(?, ?, ?, ?)}");
statement.registerOutParameter(2, Types.INTEGER);
statement.registerOutParameter(3, Types.DOUBLE);
statement.registerOutParameter(4, Types.DOUBLE);
statement.setString(1, "Java");
statement.setDouble(4, 50);
statement.execute();
Integer totalBook = (Integer) statement.getObject(2, Integer.class);
Double totalValue = statement.getDouble(3);
Double highPrice = statement.getDouble("highPrice");

System.out.println("Total books: " + totalBook);


System.out.println("Total value: " + totalValue);
System.out.println("High price: " + highPrice);

statement.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
Calling a Stored Procedure
Returning a Result Set from Java
CREATE PROCEDURE `get_books`(IN rate INT)
BEGIN
SELECT * FROM book WHERE rating >= rate;
END
CallableStatement statement = conn.prepareCall("{call
get_books(?)}");
statement.setInt(1, 5);
boolean hadResults = statement.execute();
while (hadResults) {
ResultSet resultSet = statement.getResultSet();
// process result set
while (resultSet.next()) {
// retrieve values of fields
String title = resultSet.getString("title");
}
hadResults = statement.getMoreResults();
}
Transaction Management in JDBC
If your JDBC Connection is in auto-commit mode, which it is by default, then every
SQL statement is committed to the database upon its completion.

That may be fine for simple applications, but there are three reasons why you may
want to turn off the auto-commit and manage your own transactions −

To increase performance.

To maintain the integrity of business processes.

To use distributed transactions.

Transactions enable you to control if, and when, changes are applied to the
database. It treats a single SQL statement or a group of SQL statements as one
logical unit, and if any statement fails, the whole transaction fails.
Transaction Management in JDBC
To enable manual- transaction support instead of the auto-commit mode that the
JDBC driver uses by default, use the Connection object's setAutoCommit() method. If
you pass a boolean false to setAutoCommit( ), you turn off auto-commit. You can pass
a boolean true to turn it back on again.

For example, if you have a Connection object named conn, code the following to turn
off auto-commit −\
conn.setAutoCommit(false);
Commit & Rollback
Once you are done with your changes and you want to commit the changes then call
commit() method on connection object as follows −

conn.commit( );
Otherwise, to roll back updates to the database made using the Connection named
conn, use the following code −

conn.rollback( );
try{
//Assume a valid connection object conn
conn.setAutoCommit(false);
Statement stmt = conn.createStatement();

String SQL = "INSERT INTO Employees " +


"VALUES (106, 20, 'Rita', 'Tez')";
stmt.executeUpdate(SQL);
//Submit a malformed SQL statement that breaks
throw new SQLException(“error”);
String SQL = "INSERTED IN Employees " +
"VALUES (107, 22, 'Sita', 'Singh')";
stmt.executeUpdate(SQL);
// If there is no error.
conn.commit();
}catch(SQLException se){
// If there is any error.
conn.rollback();
}
In JDBC, Connection interface provides methods
to manage transaction.

void setAutoCommit(boolean status):It is true


bydefault means each transaction is committed
bydefault.
void commit(): commits the transaction.
void rollback(): cancels the transaction.
import java.sql.*;
class FetchRecords{
public static void main(String args[])throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:
xe","system","oracle");
con.setAutoCommit(false);

Statement stmt=con.createStatement();
stmt.executeUpdate("insert into user420 values(190,'abhi',40000)");
stmt.executeUpdate("insert into user420 values(191,'umesh',50000)");

con.commit();
con.close();
}}
import java.sql.*;
import java.io.*;
class TM{
public static void main(String args[]){
try{

Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:15
21:xe","system","oracle");
con.setAutoCommit(false);

PreparedStatement ps=con.prepareStatement("insert into user420


values(?,?,?)");

BufferedReader br=new BufferedReader(new


InputStreamReader(System.in));
while(true){

System.out.println("enter id");
String s1=br.readLine();
int id=Integer.parseInt(s1);

System.out.println("enter name");
String name=br.readLine();

System.out.println("enter salary");
String s3=br.readLine();
int salary=Integer.parseInt(s3);

ps.setInt(1,id);
ps.setString(2,name);
ps.setInt(3,salary);
ps.executeUpdate();
System.out.println("commit/rollback");
String answer=br.readLine();
if(answer.equals("commit")){
con.commit();
}
if(answer.equals("rollback")){
con.rollback();
}
System.out.println("Want to add more records y/n");
String ans=br.readLine();
if(ans.equals("n")){
break;
} }
con.commit();
System.out.println("record successfully saved");
con.close();//before closing connection commit() is called
}catch(Exception e){System.out.println(e);}
JDBC - Batch Processing
Batch Processing allows you to group related SQL statements into a batch
and submit them with one call to the database.

When you send several SQL statements to the database at once, you
reduce the amount of communication overhead, thereby improving
performance.

JDBC drivers are not required to support this feature. You should use the
DatabaseMetaData.supportsBatchUpdates() method to determine if the
target database supports batch update processing. The method returns
true if your JDBC driver supports this feature.

The addBatch() method of Statement, PreparedStatement, and


CallableStatement is used to add individual statements to the batch. The
executeBatch() is used to start the execution of all the statements
grouped together.
// Create statement object
Statement stmt = conn.createStatement();

// Set auto-commit to false


conn.setAutoCommit(false);

// Create SQL statement


String SQL = "INSERT INTO Employees (id, first, last, age) " +
"VALUES(200,'Zia', 'Ali', 30)";
// Add above SQL statement in the batch.
stmt.addBatch(SQL);

// Create one more SQL statement


String SQL = "INSERT INTO Employees (id, first, last, age) " +
"VALUES(201,'Raj', 'Kumar', 35)";
// Add above SQL statement in the batch.
stmt.addBatch(SQL);

// Create one more SQL statement


String SQL = "UPDATE Employees SET age = 35 " +
"WHERE id = 100";
// Add above SQL statement in the batch.
stmt.addBatch(SQL);

// Create an int[] to hold returned values


int[] count = stmt.executeBatch();

//Explicitly commit statements to apply changes


conn.commit();
The executeBatch() returns an array of integers, and each element of
the array represents the update count for the respective update
statement.

Just as you can add statements to a batch for processing, you can
remove them with the clearBatch() method. This method removes all
the statements you added with the addBatch() method. However, you
cannot selectively choose which statement to remove.
Batching with Statement Object
Here is a typical sequence of steps to use Batch Processing with Statement
Object −

• Create a Statement object using either 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.


Batching with PrepareStatement
Object
Here is a typical sequence of steps to use Batch Processing with PrepareStatement
Object −

Create SQL statements with placeholders.

Create PrepareStatement object using either prepareStatement() 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.


// Create SQL statement
String SQL = "INSERT INTO Employees (id, first, last, age) " +
"VALUES(?, ?, ?, ?)";

// Create PrepareStatement object


PreparedStatemen pstmt = conn.prepareStatement(SQL);

//Set auto-commit to false


conn.setAutoCommit(false);

// Set the variables


pstmt.setInt( 1, 400 );
pstmt.setString( 2, "Pappu" );
pstmt.setString( 3, "Singh" );
pstmt.setInt( 4, 33 );
// Add it to the batch
pstmt.addBatch();
// Set the variables
pstmt.setInt( 1, 401 );
pstmt.setString( 2, "Pawan" );
pstmt.setString( 3, "Singh" );
pstmt.setInt( 4, 31 );
// Add it to the batch
pstmt.addBatch();

//add more batches


.
//Create an int[] to hold returned values
int[] count = stmt.executeBatch();

//Explicitly commit statements to apply changes


conn.commit();
create database empdb;
speechrecognition python - Google Search

use empdb;

create table tblemployee (empid integer primary key, firstname


varchar(32), lastname varchar(32), dob date);

insert into tblemployee values (1, 'Mike', 'Davis',' 1998-11-11');


insert into tblemployee values (2, 'Josh', 'Martin', '1988-10-22');
insert into tblemployee values (3, 'Ricky', 'Smith', '1999-05-11');
1) Forward Only
(ResultSet.TYPE_FORWARD_ONLY)
Statement stmt =
connection.createStatement(ResultSet.TYPE_FO
RWARD_ONLY, ResultSet.CONCUR_READ_ONLY);

ResultSet rs = stmt.executeQuery("select * from


tbluser");
Scroll Insensitive
(ResultSet.TYPE_SCROLL_INSENSITIVE)
Statement stmt =
connection.createStatement(ResultSet.TYPE_SC
ROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);

ResultSet rs = stmt.executeQuery("select * from


tbluser");
public class ResultSetUpdateDemo {

public static void main(String[] args) {


String query = "select empid, firstname, lastname, dob from
tblemployee";
Connection conn = null;
Statement stmt = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn =
DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/empdb",
"root", "root");
stmt =
conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery(query);
System.out.println("Now go directly to 2nd row for
Update");
if (rs.absolute(2)) {
// Go directly to 2nd row
System.out.println("Existing Name:" +
rs.getString("firstName"));
rs.updateString("firstname", "Tyson");
rs.updateRow();
}
rs.beforeFirst(); // go to start
System.out.println("All the rows of table=>");
while (rs.next()) {
// Go to next row by calling next() method
displayData(rs);
}
rs.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
stmt.close();
conn.close();
} catch (Exception e) {
}
}
}

public static void displayData(ResultSet rs) throws SQLException {


System.out.println("empId:" + rs.getInt(1));
System.out.println("firstName:" + rs.getString(2));
System.out.println("lastName:" + rs.getString(3));
System.out.println("dob:" + rs.getDate(4));
System.out.println("");
}
}
Through the java.sql.DatabaseMetaData
interface you can obtain meta data about the
database you have connected to. For instance,
you can see what tables are defined in the
database, and what columns each table has,
whether given features are supported etc.
Obtaining a DatabaseMetaData
Instance
You obtain the DatabaseMetaData object from a
Connection, like this:

DatabaseMetaData databaseMetaData =
connection.getMetaData();
Once you have obtained this DatabaseMetaData
instance, you can call methods on it to obtain
the meta data about the database.
Database Product Name and
Version
You can obtain the database product name and
version, like this:
int majorVersion =
databaseMetaData.getDatabaseMajorVersion();
int minorVersion =
databaseMetaData.getDatabaseMinorVersion();

String productName =
databaseMetaData.getDatabaseProductName();
String productVersion =
databaseMetaData.getDatabaseProductVersion();
Database Driver Version
You can obtain the driver version of the JDBC
driver used, like this:

int driverMajorVersion =
databaseMetaData.getDriverMajorVersion();
int driverMinorVersion =
databaseMetaData.getDriverMinorVersion();
Listing Tables
You can obtain a list of the defined tables in your database,
via the DatabaseMetaData. Here is how that is done:
String catalog = null;
String schemaPattern = null;
String tableNamePattern = null;
String[] types = null;
ResultSet result = databaseMetaData.getTables(
catalog, schemaPattern, tableNamePattern, types );

while(result.next()) {
String tableName = result.getString(3);
}
Listing Columns in a Table
String catalog = null;
String schemaPattern = null;
String tableNamePattern = "my_table";
String columnNamePattern = null;

ResultSet result = databaseMetaData.getColumns(


catalog, schemaPattern, tableNamePattern, columnNamePattern);

while(result.next()){
String columnName = result.getString(4);
int columnType = result.getInt(5);
}
Primary Key for Table
It is also possible to obtain the primary key of a table. You do so,
like this:

String catalog = null;


String schema = null;
String tableName = "my_table";

ResultSet result = databaseMetaData.getPrimaryKeys(


catalog, schema, tableName);

while(result.next()){
String columnName = result.getString(4);
}
JDBC Architecture

• Two-tier and Three-tier Processing Models


Three tier Architecture
Layers of the JDBC Architecture

There are four distinct types of JDBC drivers.


• JDBC drivers are divided into four types or
levels. The different types of jdbc drivers are:
• Type 1: JDBC-ODBC Bridge driver (Bridge)
Type 2: Native-API/partly Java driver (Native)
Type 3: AllJava/Net-protocol driver
(Middleware)
Type 4: All Java/Native-protocol driver (Pure)
• A JDBC driver is a software component enabling a
Java application to interact with a database
• To connect with individual databases, JDBC (the
Java Database Connectivity API) requires drivers
for each database.
• The JDBC driver gives out the connection to the
database and implements the protocol for
transferring the query and result between client
and database.
• JDBC technology drivers fit into one of four
categories.
Type 1 JDBC-ODBC Bridge.
• Type 1 drivers act as a "bridge" between JDBC and
another database connectivity mechanism such as
ODBC.
• The JDBC- ODBC bridge provides JDBC access
using most standard ODBC drivers.
• This driver is included in the Java 2 SDK within the
sun.jdbc.odbc package.
• In this driver the java statements are converted to
a jdbc statements. JDBC statements calls the
ODBC by using the JDBC-ODBC Bridge. And finally
the query is executed by the database.
• This driver has serious limitation for many
applications.
• Before a connection can be established, the bridge driver
class, sun.jdbc.odbc.JdbcOdbcDriver, must
1. either be added to the java.lang.System property named
jdbc.drivers, or
2. it must be explicitly loaded using the Java class loader.
Explicit loading is done with the following line of code:
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

• The Bridge driver uses the odbc subprotocol. URLs for this
subprotocol are of the form:
• jdbc:odbc:<data-source-name>[;<attribute-
name>=<attribute-value>]*
• For example:
jdbc:odbc:sybase
jdbc:odbc:mydb;UID=me;PWD=secret
jdbc:odbc:ora123;Cachesize=300
Function
• Translates query obtained by JDBC into
corresponding ODBC query, which is then
handled by the ODBC driver.
• Sun provides a JDBC-ODBC Bridge driver.
sun.jdbc.odbc.JdbcOdbcDriver. This driver is
native code and not Java, and is closed source.
• Client -> JDBC Driver -> ODBC Driver ->
Database
Type 2 Java to Native API.
Type 2 Java to Native API.
• Type 2 drivers use the Java Native Interface (JNI) to
make calls to a local database library API.
• This driver converts the JDBC calls into a database
specific call for databases such as SQL, ORACLE etc.
• This driver communicates directly with the database
server.
• It requires some native code to connect to the
database.
• Type 2 drivers are usually faster than Type 1 drivers.
Like Type 1 drivers, Type 2 drivers require native
database client libraries to be installed and configured
on the client machine.
Type 3 Java to Network Protocol Or All-
Java Driver.
• Type 3 drivers are pure Java drivers that use a
proprietary network protocol to communicate
with JDBC middleware on the server.
• The middleware then translates the network
protocol to database-specific function calls.
• Type 3 drivers are the most flexible JDBC
solution because they do not require native
database libraries on the client and can
connect to many different databases on the
back end.
• Type 3 drivers can be deployed over the
Internet without client installation.
Java-------> JDBC statements------> SQL
statements ------> databases.
Type 4 Java to Database Protocol.

• Type 4 drivers are pure Java drivers that


implement a proprietary database protocol
(like Oracle's SQL*Net) to communicate directly
with the database.
• Like Type 3 drivers, they do not require native
database libraries and can be deployed over
the Internet without client installation.
1. Loading a database driver,
• In this step of the jdbc connection process, we load the driver
class by calling Class.forName() with the Driver class name as an
argument.
• Once loaded, the Driver class creates an instance of itself. A client
can connect to Database Server through JDBC Driver.
• Since most of the Database servers support ODBC driver therefore
JDBC-ODBC Bridge driver is commonly used.
• The return type of the Class.forName(String ClassName) method is
"Class". Class is a class in java.lang package.

try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver"); //Or any other
driver
}
catch(Exception x){
System.out.println( "Unable to load the driver class!" );
}
• One drawback to Type 4 drivers is that they are
database specific. Unlike Type 3 drivers, if your back-
end database changes, you may save to purchase and
deploy a new Type 4 driver (some Type 4 drivers are
available free of charge from the database
manufacturer).
• However, because Type drivers communicate directly
with the database engine rather than through
middleware or a native library, they are usually the
fastest JDBC drivers available.
• This driver directly converts the java statements to SQL
statements.
• JDBC Basics - Java Database Connectivity Steps
• Before you can create a java jdbc connection to
the database, you must first import the java.sql
package.
• import java.sql.*;
• The star ( * ) indicates that all of the classes in
the package java.sql are to be imported.
• Steps:
1. Loading Driver
2. Establishing Connection
3. Executing Statements
4. Getting Results
5. Closing Database Connection
2. Creating a oracle jdbc Connection
• The JDBC DriverManager class defines objects which can connect
Java applications to a JDBC driver.
• DriverManager is considered the backbone of JDBC architecture.
• DriverManager class manages the JDBC drivers that are installed
on the system. Its getConnection() method is used to establish a
connection to a database.
• It uses a username, password, and a jdbc url to establish a
connection to the database and returns a connection object.
• A jdbc Connection represents a session/connection with a specific
database. Within the context of a Connection, SQL, PL/SQL
statements are executed and results are returned.
• An application can have one or more connections with a single
database, or it can have many connections with different
databases.
• A Connection object provides metadata i.e. information about the
database, tables, and fields. It also contains methods to deal with
transactions.
JDBC URL Syntax::
jdbc: <subprotocol>: <subname>
•Each driver has its own subprotocol
•Each subprotocol has its own syntax for the
source
• Example: For example, we're using the jdbc odbc
subprotocol, so the DriverManager knows to use
the sun.jdbc.odbc.JdbcOdbcDriver.
try{
Connection dbConnection =
DriverManager.getConnection(url, "loginName",
"Password");
} catch( SQLException x ){
System.out.println( "Couldn't get connection!" );
}
Creating a jdbc Statement object,

• Once a connection is obtained we can interact with


the database.
• Connection interface defines methods for interacting
with the database via the established connection.
• To execute SQL statements, you need to instantiate a
Statement object from your connection object by
using the createStatement() method.

Statement statement =
dbConnection.createStatement();

• A statement object is used to send and execute SQL


statements to a database.
• Three kinds of Statements
Statement: Execute simple sql queries without parameters.
Statement createStatement()
Creates an SQL Statement object.
Prepared Statement: Execute precompiled sql queries with or
without parameters.
PreparedStatement prepareStatement(String sql)
returns a new PreparedStatement object. PreparedStatement
objects are precompiled SQL statements.
Callable Statement: Execute a call to a database stored procedure.
CallableStatement prepareCall(String sql)
returns a new CallableStatement object. CallableStatement
objects are SQL stored procedure call statements.
Executing a SQL statement with the Statement object, and returning
a java ResultSet.
• Statement interface defines methods that are used to
interact with database via the execution of SQL statements.
• The Statement class has three methods for executing
statements: executeQuery(), executeUpdate(), and
execute().
1. For a SELECT statement, the method to use is
executeQuery .
2. For statements that create or modify tables, the
method to use is executeUpdate.
Note: Statements that create a table, alter a table, or
drop a table are all examples of DDL statements and are
executed with the method executeUpdate.
3. execute() executes an SQL statement that is written as
String object.
• ResultSet provides access to a table of data
generated by executing a Statement. The table
rows are retrieved in sequence. A ResultSet
maintains a cursor pointing to its current row of
data. The next() method is used to successively
step through the rows of the tabular results.
• ResultSetMetaData Interface holds information
on the types and properties of the columns in a
ResultSet. It is constructed from the Connection
object.
• import java.sql.*;

public class RetriveAllEmployees{


public static void main(String[] args) {
System.out.println("Getting All Rows from
employee table!");
Connection con = null;
String url = "jdbc:mysql://localhost:3306/";
String db = "jdbc";
String driver = "com.mysql.jdbc.Driver";
String user = "root";
String pass = "root";
try{
Class.forName(driver);
con = DriverManager.getConnection(url+db, user, pass);
Statement st = con.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM
employee");
System.out.println("Employee Name: " );
while (res.next()) {
String employeeName = res.getString("employee_name");
System.out.println(employeeName );
}
con.close();
}
catch (Exception e){
}
}
}

You might also like