Sei sulla pagina 1di 16

JDBC stands for Java Database Connectivity, which is a standard Java API for database-

independent connectivity between the Java programming language and a wide range of
databases.
The JDBC library includes APIs for each of the tasks mentioned below that are commonly
associated with database usage.
● Making a connection to a database.
● Creating SQL or MySQL statements.
● Executing SQL or MySQL queries in the database.
● Viewing & Modifying the resulting records.
The JDBC API supports both two-tier and three-tier processing models for database access but in
general, JDBC Architecture consists of two layers −
● JDBC API: This provides the application-to-JDBC Manager connection.
● JDBC Driver API: This supports the JDBC Manager-to-Driver Connection.
The JDBC API uses a driver manager and database-specific drivers to provide transparent
connectivity to heterogeneous databases.
The JDBC driver manager ensures that the correct driver is used to access each data source. The
driver manager is capable of supporting multiple concurrent drivers connected to multiple
heterogeneous databases.
Common JDBC Component
The JDBC API provides the following interfaces and classes −
● DriverManager: This class manages a list of database drivers. Matches connection
requests from the java application with the proper database driver using communication
sub protocol. The first driver that recognizes a certain subprotocol under JDBC will be
used to establish a database Connection.
● Driver: This interface handles the communications with the database server. You will
interact directly with Driver objects very rarely. Instead, you use DriverManager objects,
which manages objects of this type. It also abstracts the details associated with working
with Driver objects.
● Connection: This interface with all methods for contacting a database. The connection
object represents communication context, i.e., all communication with database is
through connection object only.
● Statement: You use objects created from this interface to submit the SQL statements to
the database. Some derived interfaces accept parameters in addition to executing stored
procedures.
● ResultSet: These objects hold data retrieved from a database after you execute an SQL
query using Statement objects. It acts as an iterator to allow you to move through its data.
● SQLException: This class handles any errors that occur in a database application.

There are four types of JDBC drivers:


● JDBC-ODBC Bridge Driver,
● Native Driver,
● Network Protocol Driver, and
● Thin Driver
1. JDBC-ODBC Driver
The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The
JDBC-ODBC bridge driver converts JDBC method calls into the ODBC function calls.
This is now discouraged because of thin driver.
Advantages:
● easy to use.
● can be easily connected to any database.
Disadvantages:
● Performance degraded because JDBC method call is converted into the ODBC function
calls.
● The ODBC driver needs to be installed on the client machine.

2.Native API Driver


The Native API driver uses the client-side libraries of the database. The driver converts
JDBC method calls into native calls of the database API. It is not written entirely in java.
Advantage:
● performance upgraded than JDBC-ODBC bridge driver.
Disadvantage:
● The Native driver needs to be installed on the each client machine.
● The Vendor client library needs to be installed on client machine.
3.Network Protocol driver
The Network Protocol driver uses middleware (application server) that converts JDBC calls
directly or indirectly into the vendor-specific database protocol. It is fully written in java.
Advantage:
● No client side library is required because of application server that can perform many
tasks like auditing, load balancing, logging etc.
Disadvantages:
● Network support is required on client machine.
● Requires database-specific coding to be done in the middle tier.
● Maintenance of Network Protocol driver becomes costly because it requires database-
specific coding to be done in the middle tier.
4. Thin driver
The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is
why it is known as thin driver. It is fully written in Java language.
Advantage:
● Better performance than all other drivers.
● No software is required at client side or server side.
Disadvantage:
● Drivers depend on the Database.
Java Database Connectivity Steps
● Register the Driver class
● Create connection
● Create statement
● Execute queries
● Close connection

1. Register the driver class


The forName() method of Class class is used to register the driver class. This method is used
to dynamically load the driver class.
Eg: Class.forName("oracle.jdbc.driver.OracleDriver");
2) Create the connection object
The getConnection() method of DriverManager class is used to establish connection with
the database.
Eg:
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","password");
3) Create the Statement object
The createStatement() method of Connection interface is used to create statement. The object
of statement is responsible to execute queries with the database.

Eg: Statement stmt=con.createStatement();


4) Execute the query
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.

Eg: ResultSet rs=stmt.executeQuery("select * from emp");

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.
Eg: con.close();

** For any java-database connectivity program use the following steps as a template **
/STEP 1. Import required packages
import java.sql.*;

public class FirstExample {


// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/EMP";

// Database credentials
static final String USER = "username";
static final String PASS = "password";
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");

//STEP 3: Open a connection


System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);

//STEP 4: Execute a query


System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);

//STEP 5: Extract data from result set


while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");

//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
//STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}
}

Example to Connect Java Application with MySql.


import java.sql.*;

class MysqlCon{

public static void main(String args[]){

try{

Class.forName("com.mysql.jdbc.Driver");

Connection con=DriverManager.getConnection(

"jdbc:mysql://localhost:3306/ncit","root","root");

//here ncit is database name, root is username and password

Statement stmt=con.createStatement();

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

while(rs.next())

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

con.close();

}catch(Exception e){ System.out.println(e);}


}

Sample code to create table


import java.sql.*;

public class JDBCExample {


// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/STUDENTS";

// Database credentials
static final String USER = "username";
static final String PASS = "password";

public static void main(String[] args) {


Connection conn = null;
Statement stmt = null;
try{
Class.forName("com.mysql.jdbc.Driver");

System.out.println("Connecting to a selected database...");


conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");

System.out.println("Creating table in given database...");


stmt = conn.createStatement();

String sql = "CREATE TABLE REGISTRATION " +


"(id INTEGER not NULL, " +
" first VARCHAR(255), " +
" last VARCHAR(255), " +
" age INTEGER, " +
" PRIMARY KEY ( id ))";

stmt.executeUpdate(sql);
System.out.println("Created table in given database...");
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
}// do nothing
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}

Sample code to update record


import java.sql.*;

public class JDBCExample {


// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost/STUDENTS";

// Database credentials
static final String USER = "username";
static final String PASS = "password";

public static void main(String[] args) {


Connection conn = null;
Statement stmt = null;
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");

//STEP 3: Open a connection


System.out.println("Connecting to a selected database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("Connected database successfully...");
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql = "UPDATE Registration " +
"SET age = 30 WHERE id in (100, 101)";
stmt.executeUpdate(sql);

// Now you can extract all the records


// to see the updated records
sql = "SELECT id, first, last, age FROM Registration";
ResultSet rs = stmt.executeQuery(sql);

while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");

//Display values
System.out.print("ID: " + id);
System.out.print(", Age: " + age);
System.out.print(", First: " + first);
System.out.println(", Last: " + last);
}
rs.close();
}catch(SQLException se){
//Handle errors for JDBC
se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
}// do nothing
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
System.out.println("Goodbye!");
}//end main
}

Result Set
A table of data representing a database result set, which is usually generated by executing a
statement that queries the database.
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 because it
returns false when there are no more rows in the ResultSet object, it can be used in a while loop
to iterate through the result set.
A default ResultSet object is not updatable and has a cursor that moves forward only. Thus, you
can iterate through it only once and only from the first row to the last row. It is possible to
produce ResultSet objects that are scrollable and/or updatable.

The object of ResultSet maintains a cursor pointing to a row of a table. Initially, cursor points to
before the first row.The ResultSet interface provides getter methods (getBoolean, getLong, and
so on) for retrieving column values from the current row. Values can be retrieved using either the
index number of the column or the name of the column. In general, using the column index will
be more efficient. Columns are numbered from 1. For maximum portability, result set columns
within each row should be read in left-to-right order, and each column should be read only once.

Methods of Result Set interface


1) public boolean next(): is used to move the cursor to the one row next from the
current position.

2) public boolean is used to move the cursor to the one row previous from the

previous(): current position.

3) public boolean first(): is used to move the cursor to the first row in result set object.

4) public boolean last(): is used to move the cursor to the last row in result set object.

5) public boolean is used to move the cursor to the specified row number in the

absolute(int row): ResultSet object.


6) public boolean is used to move the cursor to the relative row number in the

relative(int row): ResultSet object, it may be positive or negative.

7) public int getInt(int is used to return the data of specified column index of the

columnIndex): current row as int.

8) public int getInt(String is used to return the data of specified column name of the

columnName): current row as int.

9) public String is used to return the data of specified column index of the

getString(int columnIndex): current row as String.

10) public String is used to return the data of specified column name of the

getString(String current row as String.

columnName):

Prepared Statement
The PreparedStatement interface is a subinterface of Statement. It is used to execute
parameterized query. The performance of the application will be faster if you use
PreparedStatement interface because query is compiled only once

Methods of Prepared Statement

Method Description
public void setInt(int paramIndex, int sets the integer value to the given parameter index.
value)

public void setString(int paramIndex, sets the String value to the given parameter index.
String value)

public void setFloat(int paramIndex, sets the float value to the given parameter index.
float value)

public void setDouble(int sets the double value to the given parameter index.
paramIndex, double value)

public int executeUpdate() executes the query. It is used for create, drop, insert,
update, delete etc.

public ResultSet executeQuery() executes the select query. It returns an instance of


ResultSet.

Example
Sample code: Inserting id as 11 and name as ‘Arun’ in a table using prepared statement
import java.sql.*;

class InsertPrepared{

public static void main(String args[]){

try{

Class.forName("oracle.jdbc.driver.OracleDriver");

Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","or
acle");

PreparedStatement stmt=con.prepareStatement("insert into Emp values(?,?)");

stmt.setInt(1,11);//1 specifies the first parameter in the query

stmt.setString(2,"Arun");

int i=stmt.executeUpdate();

System.out.println(i+" records inserted");

con.close();

}catch(Exception e){ System.out.println(e);}

Potrebbero piacerti anche