Java Unit 6
Java Unit 6
R
Jdbc Tutorial Jdbc Architecture
JDBC
Connection
Odbc is platform dependent Jdbc is both platform and
1 Statement
and database independent. database independent.
PreparedStatement
Odbc implemented in C Jdbc implemented in java CallableStatementResultset
1
language with pointer. without pointer.
ResultSetMetaData
DatabaseMetaData
JDBC API Driver
Jdbc API is a java API that can access any kind of Blob
tabular data and specific data stored in relational
Clob
database management system (RDBMS).
Note: All Jdbc Interfaces are Implemented in Jdbc
Packages
Driver
[Link] package
Data Source Name
[Link] package
DSN (Data Source Name) is a file which stores a
Classes In Jdbc
database name. An ODBC driver uses a DSN file and
DriverManager reads a database name then connects with that
SQLException
database.
Date
1. System DSN
Java-JDBC by Kadam R.R
2. User DSN 1. Register the driver class
3. File DSN
In this step we load the JDBC driver class into JVM.
System DSN: System DSN will be stored in a This step is also called as registering the JDBC driver.
sharable location of registry and this type of DSN is The forName() method of Class class is used to
accessible for multiple user accounts of the system. register the driver class. This method is used to
dynamically load the driver class. This step can be
User DSN: User DSN will be stored in a non- completed in two ways.
sharable location of registry and this type of DSN is
only accessible for one user account of the system. [Link]("fully qualified classname")
1. Load the JDBC driver class or register the JDBC [Link] is a driver class
driver. provided by Sun MicroSystem and it can be loaded
2. Establish the connection into jvm like the following.
3. Create a statement
4. Execute the sql commands on database and get the Syntax
result
5. Print the result [Link]("[Link]
6. Close the connection r");
Java-JDBC by Kadam R.R
Syntax
1) public static Connection
getConnection(String url)throws SQLException
[Link] jod=new
[Link](); 2) public static Connection
getConnection(String url,String name,String
[Link](jod);
password)
throws SQLException
2. Create the connection object
In this step connection between a java program and a Example to establish connection with the Oracle
database will be opened. To open the connection, we database
call getConnection() method of DriverManager class.
For getConnection() method we need to pass three
Connection con=new
parameters.
[Link](url, username,
url password);
username Example:
4. Executing queries
[Link] connection : Close the connection.
Call any one of the following three methods of
Statement interface is used to execute queries to the By closing connection object statement and ResultSet
database and to get the output. will be closed automatically. The close() method of
Connection interface is used to close the connection.
executeUpdate(): Used for non-select operations.
Syntax of close() method
executequery(): Used for select operation.
Syntax of close() method
execute(): Used for both select or non-select operation.
Statement stmt=[Link]();
Example
[Link]("statement object is
cretaed");
import [Link].*;
//step-4
class CreateTable
int i=[Link]("create table
{ student(sid number(3),sname
public static void main(String[] args) throws varchar2(10),marks number(5))");
Exception //step-5
{ [Link]("Result is="+i);
//step-1 [Link]("table is created");
//step-6
[Link]("[Link] [Link]();
");
con .close();
[Link]("driver is laoded");
}
//step-2
}
Connection
con=[Link]("jdbc:odbc:
ramadsn","system","system");
Java-JDBC by Kadam R.R
Insert Images in Database fileInputStream object
you can not Insert a picture in database directly. but Size of the file
you can store binary data of picture file. To insert
image in database we need a column of type BLOB Find size of Image
(Binary Large Object). To find the size of an image file we need File class
object for that file.
Example
int size=(int)[Link]();
class PhotoInsert
Parameters of setBinaryStream()
{
parameter index
Java-JDBC by Kadam R.R
[Link]("[Link]");
File f=new File("c:/[Link]");
con=[Link]("jdbc:oracl
e:thin:@rama-pc:1521:xe","system","system"); int size=(int) [Link]();
} [Link](3,fis,size);
{ [Link](i+"row inserted");
PreparedStatement [Link]();
pstmt=[Link]("insert into }
emp_info values(?,?,?)");
public void closeCon()throws Exception
[Link]("enter emp id");
{
int empid=[Link]();
[Link]();
[Link](1,empid);
}
[Link]("enter emp name");
String empname=[Link]();
Java-JDBC by Kadam R.R
[Link]();
[Link]();
import [Link].*;
import [Link].*;
Java-JDBC by Kadam R.R
int empid=[Link](); {
[Link]();
Java-JDBC by Kadam R.R
Need of Save Point ?
}//end of select
By usning SavePoint interface we can divide a large
transaction into logically different [Link] we
public static void main(String[] args)throws want to produce one part of operations of a
Exception transaction from another part of operations of a
transaction then in the middle we put a SavePoint.
{
Advantage of SavePoint
PhotoSelect ps= new PhotoSelect();
{
Note: Multiple savepoints can exist within a single
//savepoint is supported
transaction. Savepoints are useful for implementing
complex error recovery in database applications try
Syntax {
{ try
Java-JDBC by Kadam R.R
{ {
try
int i2=[Link]("delete from student
where sid=111"); {
} [Link]();
try {
{ }
} }//end of if
{ {
Batch Processing
Method Description
void addBatch(String
1 It adds query into batch.
query)
queries.
Statement stmt=[Link]();
{ [Link]();
[Link]("Exception is"+e);
//cleanup
[Link]();
Suppose a movie ticket booking at online is a
[Link](); transaction. This task contains four operation.
Payment
Issue tickets
Java-JDBC by Kadam R.R
If all the above four operations are done successfully Consistency: Consistency means, after a
then a transaction is finished successfully. In the transaction completed with successful, the data in the
middle, if any one operation is failed then all datastore should be a reliable data this reliable data
operation are canceled and finally a transaction is is also called as consistent data.
failed.
Isolation: Isolation means, if two transaction are
Properties of Transaction managements going on same data then one transaction will not
disturb another transaction.
Every transaction follows some transaction
properties these are called ACID properties. Durability: Durability means, after a transaction is
completed the data in the data store will be
permanent until another transaction is going to be
performed on that data.
Types of Transaction
Local Transaction
To do transaction management in Jdbc, we need to Note: In transaction management DDL operation are
follow the below steps. not allowed.
Step 1: Disable auto commit mode of Jdbc Note: The operation in a transaction management
may be executed on same table or different table but
Step 2: Put all operation of a transaction in try block.
database should be same.
Step 3: If all operation are done successfully then commit
in try block, otherwise rollback in catch block. Example
{
Java-JDBC by Kadam R.R
{ {
[Link]("[Link]"); try
Connection con {
=[Link]("jdbc:oracle:th [Link]();
in:@rama-pc:1521:xe","system","system");
[Link]("Trasaction is failed");
[Link]("driver is loaded");
}
Statement stmt=[Link]();
catch (Exception ex)
[Link](false);
{
try
[Link](ex);
{
}
int i1=[Link]("insert into student
}//end of catch
values(110,'rama',685)");
[Link]();
int i2=[Link]("update customer
set custadd='Hyderabad'where custid=111"); [Link]();
Properties Files
Properties p=new Properties();
A property file is one type of the file which organizing
the data in the form of (key, value) pair. A property // Here p resides in heap memory.
file is a text file which is to be created in any editors
like-notepad, Editpuls and etc. Property file should
Advantages of Properties class over Hashtable class
be saved on same file name with on extension .prop
or .rbf. Properties class object is able to read the data from
properties/resource bundle file.
Properties Files Important points
Properties class always makes us to develop flexible
A property file is a text file which is to be created in any
application.
editors like-notepad, Editpuls and etc.
Constructor and Method of Properties class
Property file should be saved on same file name with on
extension .prop or .rbf. Constructor perporties()
Properties class object organizes the data in the form of
(key, value) pair and it displays in the same order in public void load(FileInputStream);
methods
whichever order it is added. public String get Property(String);
Example
FileInputStream fis=new
FileInputStream("student properties");
Example of properties file
[Link](fis);
import [Link].*;
public String get Property(String); is used for
import [Link].*;
obtaining the value of value by passing the key.
class Prop
try
Example {
String pfile=[Link]();
Java-JDBC by Kadam R.R
String sno=[Link]();
String sname=[Link]();
Jdbc Interview Question
String marks=[Link]();
Why use Jdbc ?
[Link]("student number="+sno);
In yearly days for communicate front end application
[Link]("student name="+sname); to database, front end application used a set of
[Link]("student marks="+marks); function given by database vendor, to connect with a
database.
[Link]();
Even today C and C++ application are connecting
}
with oracle database using a set of function given by
catch(FileNotFoundException fe) oracle corporation in a orcl.h header file.
{ But problem with the above communication is a front
[Link]("properties file does not end application become as a database dependent
exists"); application, because every database vendor give its
own set of function for communication.
}
To overcome the database dependent problem ODBC
catch(Exception e)
(Open database connectivity) community formed by
{ Microsoft with Simba technologies. ODBC
[Link](e);
Java-JDBC by Kadam R.R
community has provided ODBC API, to connect with direction forward and backward
any database in a database independent manner. direction
In database images are store in binary form. Difference between PreparedStatement and Statement ?