Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
69 views

Unit - 3: JDBC Database Programming

The document provides an overview of JDBC (Java Database Connectivity) which defines interfaces and classes for connecting Java applications to databases. It discusses the different types of JDBC drivers, the core JDBC packages, and the basic steps for establishing a database connection from Java including loading the driver, creating a connection URL, executing statements, processing result sets, and closing the connection. Key aspects of JDBC like statements, prepared statements, result sets, and transaction processing are also summarized.

Uploaded by

satwik1996
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
69 views

Unit - 3: JDBC Database Programming

The document provides an overview of JDBC (Java Database Connectivity) which defines interfaces and classes for connecting Java applications to databases. It discusses the different types of JDBC drivers, the core JDBC packages, and the basic steps for establishing a database connection from Java including loading the driver, creating a connection URL, executing statements, processing result sets, and closing the connection. Key aspects of JDBC like statements, prepared statements, result sets, and transaction processing are also summarized.

Uploaded by

satwik1996
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 65

UNIT3

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.

The JDBC API enables Java applications to


connecttorelationaldatabasesviaastandardAPI,
so your Java applications become independent
(almost)ofthedatabasetheapplicationuses.
JDBCstandardizeshowto,
connecttoadatabase
executequeriesagainstit,
navigatetheresultofsuchaqueryand
executeupdatesinthedatabase.
It does not standardize the SQL sent to the
database. This may still vary from database to
database.

JavaapplicationusingJDBCtoconnecttoadatabase

The JDBC library includes APIs for each of the tasks


commonlyassociatedwithdatabaseusage:
Makingaconnectiontoadatabase
CreatingSQLorMySQLstatements
ExecutingthatSQLorMySQLqueriesinthe
database
Viewing&Modifyingtheresultingrecords

TheJDBCAPIconsistsofthefollowingcoreparts:
JDBCDrivers
Connections
Statements
ResultSets

The JDBC API supports both twotier and threetier


processing models for database access but in general
JDBCArchitectureconsistsoftwolayers:
JDBC
API:
This
provides
the
applicationtoJDBC
Managerconnection.
JDBC Driver API: This
supports the JDBC
ManagertoDriver
Connection.

A set of Java classes that implement the


JDBC interfaces, targeting a specific
database.
The JDBC interfaces comes with standard
Java, but the implementation of these
interfacesisspecifictothedatabaseyouneed
toconnectto.
Such an implementation is called a JDBC
driver.

Fourdifferenttypes:
JDBCODBCbridgedriver
Java+Nativecodedriver
AllJava+Middlewaretranslationdriver
AllJavadriver100%pureJava

JDBCODBC bridge driver consists of a Java


part that translates the JDBC interface calls to
ODBC calls. An ODBC bridge then calls the
ODBCdriverofthegivendatabase.
Type 1 drivers are (were) mostly intended to be
used in the beginning, when there were no type 4
drivers(allJavadrivers).

Java+Nativecodedriverislikeatype1driver,
except the ODBC part is replaced with a native
codepartinstead.Thenativecodepartistargeted
ataspecificdatabaseproduct.

All Java + Middleware translation driver that


sendstheJDBCinterfacecallstoanintermediate
server. The intermediate server then connects to
thedatabaseonbehalfoftheJDBCdriver.

All Java driver which connects directly to the


database.Itisimplementedforaspecificdatabase
product. Today, most JDBC drivers are type 4
drivers.

It is not considered a deployment-level


driver and is typically used for development
Type-1
and testing purposes only.
It is useful in situations where a type-3 or
type-4
driver
is
not
available
yet
for
your
Type-2
database.
If your Java application is accessing
Type-3 multiple types of databases at the same time.
If you are accessing one type of database,
Type-4 such as Oracle, Sybase, or IBM.

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);

// Print column names.


String divider = "-----+------+-----";
System.out.println("Col1 | Col2 | Col3\n" + divider);
// Print results
while(results.next()) {
System.out.println
(pad(results.getString(1), 4) + " | " +
pad(results.getString(2), 4) + " | " +
results.getString(3) + "\n" + divider);
}
connection.close();
} catch(ClassNotFoundException cnfe) {
System.out.println("No such class: " + driver);
} catch(SQLException se) {
System.out.println("SQLException: " + se);
}
} ...

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

Through this, SQL statements are sent to the


database.
Twotypes:
Statement: for executing a simple SQL
statements.

PreparedStatement:

for executing a
precompiled SQL statement passing in
parameters.

Idea

If you are going to execute similar SQL statements


multiple times, using prepared (parameterized)
statementscanbemoreefficient
Create a statement in standard form that is sent to the
databaseforcompilationbeforeactuallybeingused
Each time you use it, you simply replace some of the
markedparametersusingthesetXxxmethods.

As PreparedStatement inherits from Statement the


correspondingexecutemethodshavenoparameters:
execute()
executeQuery()
executeUpdate()

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.

The java.sql.DatabaseMetaData interface you can


obtain meta data about the database you have
connected to and it contains a lot of methods.

Example: To see what tables are defined in the


database, and what columns each table has, whether
given
features
are
supported
etc.

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.

Exception handling allows you to handle


exceptional conditions such as program
defined errors in a controlled fashion.

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.

You might also like