Unit - 3: JDBC Database Programming
Unit - 3: JDBC Database Programming
JDBCDatabase
Programming
TheConceptofJDBC
JDBCDriverTypes
JDBCPackages
ABriefOverviewoftheJDBCprocess
DatabaseConnection
AssociatingtheJDBC/ODBCBridgewiththe
Database
StatementObjects
ResultSet
TransactionProcessing
Metadata,Datatypes
Exceptions
TheJDBCAPIdefinesinterfacesandclasses
for writing database applications in Java by
makingdatabaseconnections.
Using JDBC, one can send SQL, PL/SQL
statementstoalmostanyrelationaldatabase.
JDBC is a Java API for executing SQL
statements and supports basic SQL
functionality.
It provides RDBMS access by allowing you
toembedSQLinsideJavacode.
JavaapplicationusingJDBCtoconnecttoadatabase
TheJDBCAPIconsistsofthefollowingcoreparts:
JDBCDrivers
Connections
Statements
ResultSets
Fourdifferenttypes:
JDBCODBCbridgedriver
Java+Nativecodedriver
AllJava+Middlewaretranslationdriver
AllJavadriver100%pureJava
Java+Nativecodedriverislikeatype1driver,
except the ODBC part is replaced with a native
codepartinstead.Thenativecodepartistargeted
ataspecificdatabaseproduct.
TheJDBC2.0APIincludestwopackages:
java.sql,knownastheJDBC2.0coreAPIand
javax.sql,knownastheJDBCStandard
Extension.
Together,theycontainthenecessaryclassesto
developdatabaseapplicationsusingJava.
TheSimpleFOURsteps:
ImportJDBCPackages:AddimportstatementstoyourJava
programtoimportrequiredclassesinyourJavacode.
RegisterJDBCDriver:ThisstepcausestheJVMtoloadthe
desireddriverimplementationintomemorysoitcanfulfil
yourJDBCrequests.
DatabaseURLFormulation:Thisistocreateaproperly
formattedaddressthatpointstothedatabasetowhichyou
wishtoconnect.
CreateConnectionObject:Finally,codeacalltothe
DriverManagerobject'sgetConnection()methodtoestablish
actualdatabaseconnection.
BasicSEVENsteps:
1.Loadthedriver
2.DefinetheConnectionURL
3.EstablishtheConnection
4.CreateaStatementobject
5.Executeaquery
6.Processtheresults
7.Closetheconnection
1.Loadthedriver
try{
Class.forName("connect.microsoft.MicrosoftDriver");
Class.forName("oracle.jdbc.driver.OracleDriver");
}catch{ClassNotFoundExceptioncnfe){
System.out.println("Errorloadingdriver:"cnfe);
}
2.DefinetheConnectionURL
Stringhost="dbhost.yourcompany.com";
StringdbName="someName";
intport=1234;
StringoracleURL="jdbc:oracle:thin:@"+host+
":"+port+":"+dbName;
StringsybaseURL="jdbc:sybase:Tds:"+host+
":"+port+":"+"?SERVICENAME="+dbName;
3.EstablishtheConnection
Stringusername="jay_debesee";
Stringpassword="secret";
Connectionconnection=
DriverManager.getConnection(oracleURL,
username,
password);
4.CreateaStatement
Statementstatement=connection.createStatement();
5. ExecuteaQuery
Stringquery="SELECTcol1,col2,col3FROMsometable";
ResultSetresultSet=statement.executeQuery(query);
Tomodifythedatabase,useexecuteUpdate,supplying
astringthatusesUPDATE,INSERT,orDELETE
UsesetQueryTimeouttospecifyamaximumdelayto
waitforresults
6. ProcesstheResult
while(resultSet.next()){
System.out.println(resultSet.getString(1)+""+
resultSet.getString(2)+""+
resultSet.getString(3));
}
Firstcolumnhasindex1,not0
ResultSetprovidesvariousgetXxxmethodsthattakeacolumnindexornameand
returnsthedata
7. ClosetheConnection
connection.close();
Asopeningaconnectionisexpensive,postponethisstepifadditionaldatabase
operationsareexpected
import java.sql.*;
public class TestDB {
public static void main(String[] args) {
// Use driver from Connect SW.
String driver = "connect.microsoft.MicrosoftDriver";
try {
Class.forName(driver);
String url = "jdbc:ff-microsoft://" +
// FastForward
"dbtest.apl.jhu.edu:1433/" + // Host:port
"pubs";
// Database name
String user = "sa", password="";
Connection connection =
DriverManager.getConnection(url, user, password);
Statement statement = connection.createStatement();
String query =
"SELECT col1, col2, col3 FROM testDB";
// Execute query and save results.
ResultSet results = statement.executeQuery(query);
BasicFIVEsteps:
1.Establishaconnection
2.CreateJDBCStatements
3.ExecuteSQLStatements
4.GETResultSet
5.Closeconnections
1.Establishaconnection:
importjava.sql.*;
Loadthevendorspecificdriver
Class.forName("oracle.jdbc.driver.OracleDriver");
What do you think this statement does, and how?
Dynamically loads a driver class, for Oracle database
Maketheconnection
Connection con =
DriverManager.getConnection( "jdbc:oracle:thin:@ora
cle-prod:1521:OPROD", username, passwd);
Whatdoyouthinkthisstatementdoes?
Establishesconnectiontodatabasebyobtaining
aConnectionobject
2.CreateJDBCstatement(s):
Statementstmt=con.createStatement();
Creates a Statement object for sending SQL
statementstothedatabase.
3.ExecutingSQLStatements:
StringcreateLehigh="CreatetableLehigh"+
"(SSNIntegernotnull,NameVARCHAR(32),
"+"MarksInteger)";
stmt.executeUpdate(createLehigh);
StringinsertLehigh="InsertintoLehigh
values+
"(123456789,abc,100)";
stmt.executeUpdate(insertLehigh);
4.GetResultSet:
StringqueryLehigh="select*fromLehigh";
ResultSetrs=Stmt.executeQuery(queryLehigh);
//Whatdoesthisstatementdo?
while(rs.next()){
intssn=rs.getInt("SSN");
Stringname=rs.getString("NAME");
intmarks=rs.getInt("MARKS");
}
5.Closeconnection:
stmt.close();
con.close();
Example
Overview
AResultSetcontainstheresultsoftheSQLquery
Representedbyatablewithrowsandcolumns
InJDBC1.0youcanonlyproceedforwardthroughthe
rowsusingnext
UsefulMethods
AllmethodscanthrowaSQLException
close
ReleasestheJDBCanddatabaseresources
Theresultsetisautomaticallyclosedwhenthe
associatedStatementobjectexecutesanewquery
PreparedStatement:
for executing a
precompiled SQL statement passing in
parameters.
Idea
JDBCallowsSQLstatementstobegroupedtogetherintoa
singletransaction
Transaction controlis performed by theConnection object,
default mode is autocommit, I.e., each sql statement is
treatedasatransaction
We can turn off the autocommit mode with
con.setAutoCommit(false);
Andturnitbackonwithcon.setAutoCommit(true);
Once autocommit is off, no SQL statement will be
committeduntilanexplicitisinvokedcon.commit();
AtthispointallchangesdonebytheSQLstatementswillbe
madepermanentinthedatabase.
importjava.sql.*;
classTest{
publicstaticvoidmain(String[]args){
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");//dynamicloadingof
driver
Stringfilename="c:/db1.mdb";//LocationofanAccessdatabase
Stringdatabase="jdbc:odbc:Driver={MicrosoftAccessDriver
(*.mdb)};DBQ=";
database+=filename.trim()+";DriverID=22;READONLY=true}";//add
ontoend
Connectioncon=DriverManager.getConnection(database,"","");
Statements=con.createStatement();
s.execute("createtableTEST12345(firstcolumninteger)");
s.execute("insertintoTEST12345values(1)");
s.execute("selectfirstcolumnfromTEST12345");
ResultSetrs=s.getResultSet();
if(rs!=null)//ifrs==null,thenthereisnoResultSettoview
while(rs.next())//thiswillstepthroughourdatarowbyrow
{/*thenextlinewillgetthefirstcolumninourcurrentrow'sResultSet
asaString(getString(columnNumber))andoutputittothescreen*/
System.out.println("Datafromcolumn_name:"+rs.getString(1));
}
s.close();//closeStatementtoletthedatabaseknowwe'redonewithit
con.close();//closeconnection
}
catch(Exceptionerr){System.out.println("ERROR:"+err);}
}
}
Statementstmt=
con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
Stringquery=selectstudentsfromclasswheretype=notsleeping;
ResultSetrs=stmt.executeQuery(query);
rs.previous();//gobackintheRS(notpossibleinJDBC1)
rs.relative(5);//go5recordsback
rs.relative(7);//go7recordsforward
rs.absolute(100);//goto100threcord
Statementstmt=
con.createStatement(ResultSet.TYPE_FORWARD_ONLY,
ResultSet.CONCUR_UPDATABLE);
Stringquery="selectstudents,gradefromclass
wheretype=reallylisteningthispresentation;
ResultSetrs=stmt.executeQuery(query);
while(rs.next())
{
intgrade=rs.getInt(grade);
rs.updateInt(grade,grade+10);
rs.updateRow();
}
AConnection'sdatabaseisableto
provideschemainformation
describingitstables
itssupportedSQLgrammar
itsstoredprocedures
thecapabilitiesofthisconnection,andsoon
Thisinformationismadeavailable
throughaDatabaseMetaDataobject.
JDBCMetaDataAPIs:
Connection:
DatabaseMetaDatagetMetaData()
ResultSet:
ResultSetMetaDatagetMetaData()
ObtainingaDatabaseMetaDataInstance:
DatabaseMetaData databaseMetaData =
connection.getMetaData();
DatabaseProductNameandVersion
intmajorVersion=
databaseMetaData.getDatabaseMajorVersion();
intminorVersion=
databaseMetaData.getDatabaseMinorVersion();
StringproductName=
databaseMetaData.getDatabaseProductName();
StringproductVersion=
databaseMetaData.getDatabaseProductVersion()
DatabaseDriverVersion
intdriverMajorVersion=
databaseMetaData.getDriverMajorVersion();
intdriverMinorVersion=
databaseMetaData.getDriverMinorVersion();
DatabaseProductNameandVersion
intmajorVersion=
databaseMetaData.getDatabaseMajorVersion();
ListingTables
ListingColumnsinaTable
PrimaryKeyforTable
SupportedFeatures
Connectioncon=.;
DatabaseMetaDatadbmd=con.getMetaData();
Stringcatalog=null;
Stringschema=null;
Stringtable=sys%;
String[]types=null;
ResultSetrs=
dbmd.getTables(catalog,schema,table,types);
publicstaticvoidprintRS(ResultSetrs)throwsSQLException
{
ResultSetMetaDatamd=rs.getMetaData();
//getnumberofcolumns
intnCols=md.getColumnCount();
//printcolumnnames
for(inti=1;i<nCols;++i)
System.out.print(md.getColumnName(i)+",");
//outputresultset
while(rs.next())
{ for(inti=1;i<nCols;++i)
System.out.print(rs.getString(i)+",");
System.out.println(rs.getString(nCols));
}
}
TheJDBCdriverconvertstheJavadata
typetotheappropriateJDBCtypebefore
sending it to the database. It uses a
defaultmappingformostdatatypes.
Example: int is converted to an SQL
INTEGER.
Default mappings were created to
provideconsistencybetweendrivers.
ThefollowingtablesummarizesthedefaultJDBCdatatypethattheJavadatatypeis
converted to when you call the setXXX() method of the PreparedStatement or
CallableStatementobjectortheResultSet.updateXXX()method.
JDBCExceptionhandlingisverysimilarto
JavaExceptionhandlingbutforJDBC,the
mostcommonexceptionyou'lldealwithis
java.sql.SQLException.
ExceptionHandling
SQLExceptions
Nearly every JDBC method can throw a
SQLExceptioninresponsetoadataaccesserror.
Ifmorethanoneerroroccurs,theyarechainedtogether
SQLexceptionscontain:
Descriptionoftheerror,getMessage
TheSQLState(OpenGroupSQLspecification)identifyingthe
exception,getSQLState
Avendorspecificinteger,errorcode,getErrorCode
AchaintothenextSQLException,getNextException
SQLExceptionExample
try{
...//JDBCstatement.
}catch(SQLExceptionsqle){
while(sqle!=null){
System.out.println("Message:"+sqle.getMessage());
System.out.println("SQLState:"+sqle.getSQLState());
System.out.println("VendorError:"+
sqle.getErrorCode());
sqle.printStrackTrace(System.out);
sqle=sqle.getNextException();
}
}
Dontmakeassumptionsaboutthestateofatransactionafteranexception
occurs.
Thesafestbestistoattemptarollbacktoreturntotheinitialstate.
SQLWarnings
SQLWarnings are rare, but provide information about the
databaseaccesswarnings
Chainedtoobjectwhosemethodproducedthewarning
Thefollowingobjectscanreceiveawarning:
Connection
Statement
ResultSet
Call getWarning to obtain the warning object, and
getNextWarning (on the warning object) for any additional
warnings
Warnings are cleared on the object each time the statement is
executed
SQLWarningExample
ResultSetresults=statement.executeQuery(someQuery);
SQLWarningwarning=statement.getWarnings();
while(warning!=null){
System.out.println("Message:"+warning.getMessage());
System.out.println("SQLState:"+warning.getSQLState());
System.out.println("VendorError:"+warning.getErrorCode());
warning=warning.getNextWarning();
}
while(results.next()){
intvalue=rs.getInt(1);
...//Calladditonalmethodsonresultset.
SQLWarningwarning=results.getWarnings();
while(warning!=null){
System.out.println("Message:"+warning.getMessage());
System.out.println("SQLState:"+warning.getSQLState());
System.out.println("VendorError:"+warning.getErrorCode());
warning=warning.getNextWarning();
}
}
SQLExceptionMethods:
ASQLExceptioncanoccurbothinthedriverandthe
database.Whensuchanexceptionoccurs,anobjectof
typeSQLExceptionwillbepassedtothecatchclause.
Summary
In JDBC 1.0, can only step forward (next) through the
ResultSet
Be sure to handle the situation where getXxx returns a
NULL
Understandtherelationshipbetween:
Connectionobject
Statementobject
ResultSetobject
Bydefault,aconnectionisautocommit.
SQLExceptionsandWarningsarechainedtogether.