Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
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.
** For any java-database connectivity program use the following steps as a template **
/STEP 1. Import required packages
import java.sql.*;
// 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");
//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!");
}
}
class MysqlCon{
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/ncit","root","root");
Statement stmt=con.createStatement();
while(rs.next())
con.close();
// Database credentials
static final String USER = "username";
static final String PASS = "password";
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
}
// Database credentials
static final String USER = "username";
static final String PASS = "password";
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.
2) public boolean is used to move the cursor to the one row previous from the
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
7) public int getInt(int is used to return the data of specified column index of the
8) public int getInt(String is used to return the data of specified column name of the
9) public String is used to return the data of specified column index of the
10) public String is used to return the data of specified column name of the
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
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.
Example
Sample code: Inserting id as 11 and name as ‘Arun’ in a table using prepared statement
import java.sql.*;
class InsertPrepared{
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","or
acle");
stmt.setString(2,"Arun");
int i=stmt.executeUpdate();
con.close();