You are on page 1of 38

Connecting to a

Database Using the


JDBC API

Aris Global Aris Global Confidential


Setting up a Database Connection

• JDBC provides a server-independent approach to


database access.
• To use JDBC, you will need
 a database server
 a database driver.
• The JDBC comes with a JDBC-ODBC bridge. This
bridge allows you to access databases via Microsoft’s
Open Database Connectivity API.

Aris Global Aris Global Confidential


The DriverManager Class

• A class of java.sql package is responsible


for selecting database drivers and creating a
new database connection.
• Before the driver manager activate a driver, the
driver must be registered.

Aris Global Aris Global Confidential


The DriverManager Class
Continued…
There are two methods for registering the drivers:
 A program can set the system property by
Properties class of java.util package.
 Manually register a driver using Class class.

• The DriverManager class does not provide a


constructor, and all of it’s methods are static.

Aris Global Aris Global Confidential


The DriverManager Class
Continued…
• The getConnection() method is used to
establish a connection to a database. This
method is provided in the following forms:

 getConnection(String url)
 getConnection(String url, String
userID, String password)
 getConnection(String url, Properties
arguments)

Aris Global Aris Global Confidential


Methods defined by the DriverManager class
Methods Description

getDriver() Returns a driver that can support a connection via a


specified URL.
registerDriver() Invoked by drivers to register themselves with
DriverManager.
deregisterDriver() Invoked by drivers to deregister themselves with
DriverManager.
getDrivers() Retrieves an Enumeration with all of the currently loaded
JDBC drivers to which the current caller has access.

GetLoginTimeout() Gets the maximum time in seconds that a driver can wait
when attempting to log in to a database.

SetLoginTimeout() Sets the maximum time in seconds that a driver will wait
while attempting to connect to a database.

getLogWriter() JDBC 2.0 Gets the log writer.

setLogWriter(Print JDBC 2.0 Sets the logging/tracing Writer that is used by


Writer out) the DriverManager and all drivers.

println() Prints a message to the current JDBC log stream.

Aris Global Aris Global Confidential


The Driver Interface
The Driver interface is implemented by JDBC
drivers.

Methods Description

connect() Attempts to make a database connection to


the given URL.
acceptsURL(String Returns true if the driver thinks that it can
URL) open a connection to the given URL.
getPropertyInfo(Stri Gets information about the possible
ng URL , Properties properties for this driver.
info)
getMajorVersion() Gets the driver's major version number.

getMinorVersion() Gets the driver's minor version number.

jdbcCompliant() Reports whether this driver is a genuine


JDBC COMPLIANTTM driver.

Methods defined by the DriverManager class


Aris Global Aris Global Confidential
Example
The DriverDetail Program
you will get the information about the driver.

import java.sql.*;
import java.util.*;

class DriverDetail {
public static void main(String args[]) {
try{
//Registring the driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Aris Global Aris Global Confidential


Example
Continued…
//get the list of drivers
Enumeration drivers =
DriverManager.getDrivers();
System.out.println("Available drivers:");
while(drivers.hasMoreElements()){
Driver driver=(Driver)drivers.nextElement();
System.out.println(" Driver:
"+driver.getClass().getName());
System.out.println(" Major version:
"+driver.getMajorVersion());

Aris Global Aris Global Confidential


Example
Continued…

System.out.println(" Minor version:


"+driver.getMinorVersion());
System.out.println(" JDBC compliant:
"+driver.jdbcCompliant());

}catch(Exception ex){
System.out.println(ex);
System.exit(0);
}
}//PSVM
}//Class

Aris Global Aris Global Confidential


The Connection Interface
The Connection interface
• defines methods for interacting with the
database connection.
• defines several constants that describe the
manner in which the database supports the
committing of database transactions.

Aris Global Aris Global Confidential


Methods defined by the Connection interface
Methods Description

close() Releases a Connection's database and JDBC resources


immediately instead of waiting for them to be
automatically released.
getMetaData() Gets the metadata regarding this connection's database.

createStatement Creates a Statement object for sending SQL statements


() to the database.

prepareStateme Creates a PreparedStatement object for sending


nt(String sql) parameterized SQL statements to the database.

prepareCall(Str Creates a CallableStatement object for calling


ing sql) database stored procedures.

setAutoCommit Sets this connection's auto-commit mode.


(boolean
autocommit)

rollback() Drops all changes made since the previous


commit/rollback and releases any database locks currently
held by this Connection.

commit() Makes all changes made since the previous


commit/rollback permanent and releases any database
locks currently held by the Connection.

Aris Global Aris Global Confidential


The DatabaseMetaData Interface

It provides the methods to get the


information about the database to which a
connection is established.

Aris Global Aris Global Confidential


Methods Description

getDatabaseProductN Returns the name of the database


ame() product?

getDtabaseProductVe Returns the version of the database


rsion() product?

getUserName() Returns our user name as known to


the database?

getDriverName() Returns the name of the JDBC driver?

getDriverVersion() Returns the version of the JDBC


driver?
getImportedKeys(Stri Gets a description of the primary key
ng catalog, String columns that are referenced by a
schema, String table) table's foreign key columns (the
primary keys imported by a table).

Methods of the DatabaseMetaData interface


Aris Global Aris Global Confidential
Example
The ConnectMeta Program
you will get the information about the driver and
the database.

For this example first you have to create


• a database “emp”
• register the *.mdb file with jdbc.odbc driver by
default available in control panel.

Aris Global Aris Global Confidential


Example
import java.sql.*;
import java.util.*;

class ConnectMeta {
public static void main(String args[]) {
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection
connection=DriverManager.getConnection("jdbc:
odbc:anuj","","");
DatabaseMetaData
meta=connection.getMetaData();

Aris Global Aris Global Confidential


Example
Continued…
System.out.print("Database :
"+meta.getDatabaseProductName());
System.out.println("Database Product Version
:"+meta.getDatabaseProductVersion());
System.out.println("Driver name : "+meta.getDriverName());
System.out.println("Driver version :
"+meta.getDriverVersion());
System.out.println("Max Column Length :
"+meta.getMaxColumnNameLength());
System.out.println("Max Row Size :
"+meta.getMaxRowSize());
connection.close();
}catch(Exception ex){
System.out.println(ex);
System.exit(0);
}
}
Aris Global Aris Global Confidential
Working with Result Sets

The ResultSet interface


• is used to provide access to this tabular data.
• provides the access one row at a time.
• is used to move the cursor in either direction of
the table

Aris Global Aris Global Confidential


Methods defined by ResultSet interface
Methods Description

deleteRow() JDBC 2.0 Deletes the current row from the result
set and the underlying database.
findColumn(Strin Maps the given Resultset column name to its
g columnName) ResultSet column index.

close() Releases this ResulSet

findColumn(String Maps the given Resultset column name to its


columnName) ResultSet column index.

next ( ) Moves the cursor down one row from its current
position.
previous() Moves the cursor in the backward direction

first() Moves to the first result

last() Moves to the last result

afterLast() Moves to the end point

beforeFirst() Moves to the stating point

getInt(int Gets the value of a column in the current row as a


columnIndex) Java int.

Aris Global Aris Global Confidential


The ResultSetMetaData Interface

The ResultSetMetaData interface provide


constants and methods that are used to
obtain information about ResultSet objects

Aris Global Aris Global Confidential


Methods Description

getColumnCount() Returns the number of columns in this


ResultSet.
getColumnName(in Gets a column's name.
t columnName)

getCoulmnType(int Retrieves a column's SQL type.


columnName)

getTableName(int Gets a column's table name.


columnNmae)

isCurrency(int Indicates whether the column is a cash


columnName ) value.

Methods defined by the


ResultSetMetaData interface
Aris Global Aris Global Confidential
Example
The ResultSet1 Program
import java.sql.*;
import java.util.*;

class ResultSet1 {
public static void main(String args[]) {
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection
con=DriverManager.getConnection("jdbc:odbc:anuj","","");
Statement stmt = con.createStatement();

ResultSet rs = stmt.executeQuery("SELECT * FROM emp");


while(rs.next()){

Aris Global Aris Global Confidential


Example
Continued…
String s=rs.getString("empName");
int n=rs.getInt("empId");
System.out.println("Employee Name = " + s);
System.out.println("Employee Id = " + n);
}
con.close();
}catch(Exception ex){
System.out.println(ex);
System.exit(0);
}
}
}

Aris Global Aris Global Confidential


Executing SQL Statements

SQL statement is used to interact with


database servers.

Aris Global Aris Global Confidential


The Statement Interface

It defines methods that are used to interact with


databases via the execution of SQL statements.

• The createStatement() method returns the


object of Statement interface.
• Using this object you invoke the
executeQuery() method

Aris Global Aris Global Confidential


Methods Description

execute(String sql) Executes a SQL statement that may


return multiple results.

executeUpdate(String sql) Executes an SQL INSERT,


UPDATE or DELETE statement.

executeQuery(String sql) Executes a SQL statement that


returns a single ResultSet. (such as
SELECT statement)

getResultSet() Returns the current result as a


ResultSet object.

getUpdateCount() Returns the current result as an


update count; if the result is a
ResultSet or there are no more
results, -1 is returned.
getMoreResults() Moves to a Statement's next result.

Methods defined by the Statement interface


Aris Global Aris Global Confidential
The PreparedStatement Interface

• The PreparedStatement interface extends the


Statement interface.
• A pre compiled SQL statement is stored in a
PreparedStatement object.
• This object can be used to efficiently execute this
statement multiple times.

Aris Global Aris Global Confidential


The PreparedStatement Interface
Continued…
• To use the PreparedStatement interface Create a object -
PreparedStatement ps =
cn.PrepareStatement(“UPDATE emp SET ename= ?
WHERE eno = ?”);
//here cn is a connection object

• Supply the values for parameters –


Ps.setString(1,”Tom”);
Ps.setInt(2,101);

Aris Global Aris Global Confidential


Methods Description

getMetaData() Gets the number, types and


properties of a ResultSet's columns.

setDate(int parameterIndex, Date Sets the designated parameter to a


x) java.sql.Date value

setInt(int parameterIndex, int x) Sets the designated parameter to a


Java int value

setArray(int I, Array x ) Sets an array parameter

setObject(int parameterIndex, Sets the value of a parameter using


object x) an object; use the java.lang
equivalent objects for integral
values.

Methods defined by the


PreparedStatement interface
Aris Global Aris Global Confidential
Example
import java.sql.*;
import java.util.*;
class Prepare {
public static void main(String args[]) {
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection
con=DriverManager.getConnection("jdbc:odbc:anuj","","
");
Statement stmt = con.createStatement();
PreparedStatement ps=con.prepareStatement("UPDATE
emp SET empName =? WHERE empID =? ");

Aris Global Aris Global Confidential


Continued…

ps.setString(1, "Tom");

ps.setInt(2,3);

ps.executeUpdate();

ResultSet rs = stmt.executeQuery("SELECT * FROM emp");

while(rs.next()){

String s=rs.getString("empName");

int n=rs.getInt("empID");

System.out.println("Employee Name = " + s);

System.out.println("Employee Id = " + n);

} con.close();

Aris Global Aris Global Confidential


Continued…
//Here 1 and 2 are the sequential number of values to be
set.
}catch(Exception ex){
System.out.println(ex);

System.exit(0);

Aris Global Aris Global Confidential


The CallableStatement Interface

• This interface extends the PreparedStatement


interface.
• The CallableStatement object contains a call
to a stored procedure in the database.
• A stored procedure is passed as an argument to
the prepareCall() method of the Connection
interface.

Aris Global Aris Global Confidential


Continued…

• A stored procedure call may take


 IN parameters
 OUT Parameters
 INOUT parameters.
• Each OUT parameter must be registered in a log
file using registerOutParameter().

Aris Global Aris Global Confidential


Transaction Processing

• It is a group of related database operations.


• It update the database at the same time.
• It does not permanently update untill they are
committed.
• If an error occurs during the transaction,
transaction can be rolled back.

Aris Global Aris Global Confidential


New D/B
SQL Query On Commit
Database to update the
table

Old D/B
On Rollback

Execution of the transaction

Aris Global Aris Global Confidential


Continued…
The key methods used to implement transaction
processing:
• commit()
complete the transaction by executing the
Statement
• rollback()
reverses the transaction that is in progress by
erasing the
effects of SQL statements
• setAutoCommit()
makes automatic committing of SQL statement

Aris Global Aris Global Confidential


Summary

In this session you have learnt to


• describe Java’s mechanism for connecting to a
database.
• describe the processing of retrieved data.
• describe the process of executing SQL
statements from within a Java program.
• describe java.sql’s support for transaction
processing.

Aris Global Aris Global Confidential

You might also like