You are on page 1of 23

JAVA Software

Development Paradigm
Advance OO Programming
BSCS Semester 6
MCS 3
Course Instructor: Ms. Iram

JDBC
The JDBC ( Java Database Connectivity)
An API that defines interfaces and classes for
writing database applications in Java by
making database connections.
Works with almost any relational database.
JDBC is a Java API for executing SQL
statements and supports basic SQL
functionality.

JDBC Architecture

JDBC Basics
import java.sql.*;
Steps
1. Loading a database driver
2. Creating a jdbc Connection
3. Creating a jdbc Statement object
4. Executing a SQL statement with the Statement
object, and returning a jdbc resultSet
5. Extract data from result set
6. Clean-up environment

Database driver string


Samples
mySQL = com.mysql.jdbc.Driver

Sqlserver =
com.microsoft.jdbc.sqlserver.SQLServerDriver
Apache Derby = org.apache.derby.jdbc.ClientDriver
MS-Access (32 bit) = sun.jdbc.odbc.JdbcOdbcDriver
MS-Access (64 bit) =
Provider=Microsoft.ACE.OLEDB.12.0 http://
www.microsoft.com/downloads/details.aspx?Family
ID=C06B8369-60DD-4B64-A44B-84B371EDE16D&displa
lang=en

Or any other DBMS driver

DB Connection URL
Samples
General format:

jdbc:sqlserver://server:port;DatabaseName=dbna
me
mysql = jdbc:mysql://localhost/dbname
Sql server =
jdbc:microsoft:sqlserver://localhost:1433;databa
seName=dbname
ms access = jdbc:odbc:Emp
Derby = jdbc:derby://localhost:1527/DBname

1. Loading a database driver


try {
Class.forName(DB driver string path);
}
Catch(Exception e)
{
System.out.println(unable to load the
driver);
}

2. Creating a jdbc Connection


try{
Connection dbCon = null;
dbCon = DriverManager.getConnection(DB
conneciton URL ,user,pw)
}
catch( SQLException x ){
System.out.println( Couldnt get connection! );
}

3. Creating a jdbc Statement object


Statement stmt = dbCon.createStatement();
4. Executing a SQL statement
String s = "SELECT id, first, last, age FROM
Employees;
ResultSet rs = stmt.executeQuery(s);

5. Extract data from result set


while(rs.next() ) {
//Retrieve by column name
System.out.print(id = +rs.getInt("id") );
System.out.print(age = + rs.getInt("age") );
System.out.print(fname = +
rs.getString("first") );
System.out.print(l name = +
rs.getString("last") );
}

STEP 6: Clean-up environment


rs.close(); // close result set
stmt.close(); // close db statement
dbCon.close(); // close db connection
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
if(stmt!=null)
stmt.close();
if(dbCon!=null)
conn.close();
} // end finally

Complete Code Structure

try{
static final String DBDriver = DB Driver string;
static final String DBCon = DB connection string;
String sqlQuery = "SELECT id, first, last, age FROM Employees";
Class.forName(DB driver string path); // load driver
Connection dbCon =
DriverManager.getConnection(DBcon,loginName,Password) ; // get
connection
Statement stmt = dbCon.createStatement(); // create statement
ResultSet rs = stmt.executeQuery(sqlQuery); // create result set
while(rs.next() ) {
//Retrieve data from result set
}
rs.close();
// close result set
stmt.close();
// close db statement
dbCon.close();
// close db connection
}
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
if(stmt!=null)
stmt.close();
if(dbCon!=null)
conn.close();

JDBC Statement Types


Statement
Prepared Statement
Callable Statement

Statement:
Execute simple sql queries without parameters.
Syntax : Statement createStatement()
Prepared Statement:
Execute precompiled sql queries with or without
parameters.
Syntax : PreparedStatement
prepareStatement(String sql)
Callable Statement:
Execute a call to a database stored procedure.
Syntax : CallableStatement prepareCall(String sql)

Statement
Use for general-purpose access to your database.
Execute simple sql queries without parameters.
you can then use it to execute a SQL statement with one of
its three execute methods.
Syntax :
stmt = conn.createStatement( );
stmt.close();

you can then use it to execute a SQL statement with one of its three
execute methods.
boolean execute(String SQL) :
Use this method to execute SQL DDL statements or when you need
to use truly dynamic SQL.
int executeUpdate(String SQL) :
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.

Result Sets Details


A ResultSet is a tabular structure
containing the dataset returned by
executing a query statement.
It contains both the data itself and
metadata.
A ResultSet object is read-only and
forward-only by default.

Result Set cont..


The ResultSet object provides the necessary
methods to:
iterate over the rows both forward and backward.
read or update each column content.
insert new rows into the ResultSet and finally into
the underlying table.
delete rows from the ResultSet and the
underlying table.
Read the metadata associated with the ResultSet
jump between rows by providing the absolute row
number.

ResultSet How To?


ResultSetMetaData rsmd = null;
How to get total columns returned in a
ResultSet ?
rsmd.getColumnCount() ;

How to get column names for rows returned in


a ResultSet ?
rsmd = rs.getMetaData();
String value = rsmd.getColumnName(1);

ResultSet How To?


How do I create an updatable
ResultSet?
Some conditions apply to the updatable
ResultSet: The SELECT statement must have a single underlying table;
no joins and no aggregation functions are allowed.
The PK of the underlying table must be present in the
ResultSet so it can propagate the changes to the correct
row in the table.

Statement stmt =
connection.createStatement( ResultSet.TYPE_S
CROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);

ResultSet How To?


How can I update a ResultSet
programmatically?
Statement stmt =
conn.createStatement(ResultSet.TYPE_SCROLL_SENSIT
IVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("SELECT name
,lastName ,sn FROM table_1");
rs.absolute(5); //moving the cursor to the first row
rs.updateString("name", john); // update the name field
of the current row

rs.updateRow(); //persist the change

Create Statement
Arguments
The first argument in CreateStatement indicates the type of
the ResultSet object :
TYPE_FORWARD_ONLY: The ResultSet will only allow the cursor to go forward.
TYPE_ SCROLL_INSENSITIVE: The cursor can scroll forwards and

backwards, and the result set is not sensitive to changes made by others
to the database that occur after the result set was created.
TYPE_SCROLL_SENSITIVE: The cursor can scroll forwards and
backwards, and the result set is sensitive to changes made by others to
the database that occur after the result set was created.

The second argument in CreateStatement indicates whether


the ResultSet is updatable or not. The following values are
acceptable for this parameter:
CONCUR_READ_ONLY: A ResultSet of this type is readonly
CONCUR_UPDATABLE : We can update the resultset created with this value
for the mentioned parameter.

We can iterate forward in this ResultSet


using the following snippet
while (rs.next()) {
String name = rs.getString("name");
String lastName = rs.getString ("lastName");
String sn = rs.getString(sn);
System.out.println(name + " " + lastName + +sn);

Use rs.previous() instead of rs.next to


iterate backword.
Delete a specific row
rset.absolute(5);
rset.deleteRow();

To execute a query to update a table


or delete some row in the table use
Resultset.executeupdate() function.

You might also like