Adv CH-1 JDBC
Adv CH-1 JDBC
Adv CH-1 JDBC
The process of storing data in permanent storage and using that data in our applications is called persistence.
Persistence Storage :- The storage where data can be stored and managed permanently is called
persistence storage.
Persistence Logic :- The logic that is developed in the application to interact with persistence
storage and to manipulate data in persistence storage is called persistence logic.
Persistence Operation: - Insert, Update, Select and Delete operation perform in data of
persistence store are called persistence operation.
Java application uses IO streams based persistence logic to interact with files.
Java application uses JDBC based persistence logic to interact with database software.
In small scale applications use files as persistence store.
In medium scale and large scale application use database software as persistence store.
DB SOFTWARE VENDOR
Oracle Oracle corporation
My SQL Sun micro System
SQL server Microsoft
DB2 IBM
Postgre Open symphony
App data is nothing but input values coming to application & the results generated by the application. If this
data is not saved in persistence store like file or db software, we will lose this data at the end of the app
execution. To solve this problem , we perform persistence operation on app data.
JDBC is a open specification containing rule and guidelines to develop JDBC driver, so any software vendor can
develop JDBC driver because it is open specification. For every DB software we need one separate JDBC drivers.
What is ODBC(open data base connectivity) ? - ODBC is an open specification containing rules and
guidelines to develop odbc drivers for different DB software.
When all other technologies based application are using odbc drivers to interact with DB software why java apps
are separately looking for JDBC drivers ?, because Odbc drivers are given based on c-language. So they take
the support of pointers since java does not support pointers, hence java application needs separate java based JDBC
drivers to interact with DB software.
9437100566/7205203460
JDBC : By Mr. Gitesh Kumar Mallick @ LAKSHYA 2
Step-1:- Import the java.sql package which contains all the classes and interfaces for database connection.
Step-2:- Load the driver by the static method called forName() of Class given below
Class.forName (String Driver name) throws ClassNotFoundException;
Q:- In the above statement Class.forName() method just loads the jdbc driver class. Then how can we say
jdbc driver is registred with DriverManager service at the end of that statement execution.
ANS:- The forName() loads given jdbc Driver class, because of this loading the static block of driver class
executes automatically, & this static block contains the logic to create jdbc driver class obj and logic to register
that driver class obj with DriverManager service by calling DriverManager.registerDriver().
NOTE:- All vendors supplied jdbc drivers for different DB s/ws contains static blocks havi ng some jdbcDriver
registration code in respective jdbcDriver classes.So, the programmer can use the above given class.forName()
approach to load JdbcDriver class to register that Jdbc driver with DriverManager service.
Step-3:- Establish a logical connection between the java program & the database by getConnection() of
DriverManeger class.
Connection con=DriverManager.getConnection (String JDBCURL, String username, String password);
9437100566/7205203460
JDBC : By Mr. Gitesh Kumar Mallick @ LAKSHYA 3
e.g.: Connection con=DriverManager.getConnection(“jdbc:oracle:thin:@localhost:1521:xe”, "system",
"manager");
The string parameter JDBCURL contains address, name of the driver. The second and third parameter is
optional because, the getConnection() is overloaded in DriverManager class which may not accept the 2nd and 3rd
parameter.
In case of Microsoft Access, we may not provide the username and password. In that case, the 2nd and 3rd
parameter on the above method may be null string or we may use one argument getConnection(). The Connection
is an interface that behaves like a logical connection between the java and DBMS.
Step-5:- Once all the job will complete, we have to close Connection by following statement
con.close ();
Using Mysql :
import java.sql.*;
9437100566/7205203460
JDBC : By Mr. Gitesh Kumar Mallick @ LAKSHYA 4
class Mysqlconn {
public static void main(String args[]) throws Exception {
Class.forName("oracle.jdbc.driverOracleDriver");
Connection con = DriverManager.getConnection( " jdbc:mysql://localhost/college", "root", "");
Statement st = con.createStatement();
ResultSet rs=st.executeQuery("select * from student");
while(rs.next())
System.out.println(rs.getString("name")+" \t"+rs.getInt("roll") + "\t"+ rs.getString("sem")+"\t"+
rs.getFloat("mark"));
con.close();
}};
Using Oracle
import java.sql.*;
class OraConn {
public static void main(String args[]) throws Exception {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","system", "manager");
Statement stmt= con.createStatement();
ResultSet rs=stmt.executeQuery("select * from student");
while(rs.next()){
System.out.println(rs.getString("name")+" \t"+rs.getInt("roll") + "\t"+ rs.getString("sem")+"\t"+
rs.getFloat("mark"));
}
con.close();
}};
--> store the file with .java extn
--> copy the classes111.jar(for oracle 8i) classes12.jar(for oracle 9i) or ojdbc6.jar/ojdbc14.jar(for oracle 10g/11g)
from oracle installation folder( ex: if oracle is installed under D:\ then the .jar file avaialable in
D:\oracle\ora90\jdbc\lib) to the same folder where the .java file is stored.
--> compile the above file from dos as
javac -cp classes12.jar;. OraConn.java
-->Execute as
java -cp classes12.jar;. OraConn
9437100566/7205203460
JDBC : By Mr. Gitesh Kumar Mallick @ LAKSHYA 5
@localhost refers to IPAddress of the local machine, but if oracle DB is installed in different machine then we
should provide ipaddress something like 192.168.10.4 instead of localhost, but the @ symbol must precede the
ipaddress.
1521 is the default port number on which the type-iv driver(thin) or type-ii driver(oci) gnerally runs.
XE is the host string(or SID- System Identifier) of this machine. To know the SID, open control panel -
adminstrative tool - services. In services u'll get OracleServiceZZZ, ZZZ will be the SID.
Data fetching methods of ResultSet:- These method of the ResultSet are used to fetch the data from the
different columns of the tables.
1. public String getString(String columnName/ int column_no);
2. public int getInt(String columnName/ int column_no);
3. public byte getByte(String columnName/ int column_no);
4. public short getShort(String columnName/ int column_no);
5. public long getLong(String columnName/ int column_no);
6. public float getFloat(String columnName/ int column_no);
7. public double getDouble(String columnName/ int column_no);
8. public Date getDate(String columnName/ int column_no);
9. public Date getObject(String columnName/ int column_no);
Note:- The above column index/no.s must refer the column no. of select qry, not that of database
import java.sql.*;
class Data3{
public static void main(String args[])throws Exception {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/college,"root","");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select a.*,b.* from emp a, dept b where a.deptno=b.deptno");
while(rs.next())
System.out.println(rs.getInt(1) +"\t" +rs.getString(2)+"\t"+rs.getDate(3)
+"\t"+rs.getFloat(5)+"\t"+rs.getString(7)+"\t"+rs.getString(8) ));
con.close();
}};
Inserting a Record :
import java.sql.*;
import java.util.Scanner;
class Data3{
public static void main(String args[])throws Exception {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/college,"root","");
Statement st=con.createStatement();
Scanner s=new Scanner(System.in);
System.out.println(“enter name”);
String na=s.next();
System.out.println(“enter roll”);
int ro =s.nextInt();
System.out.println(“enter sem”);
String se = s.next();
System.out.println(“enter sem”);
float ma=s.nextFloat();
String qry="insert into student values('"+na+"', "+ro+",'"+se+"', "+ma+")";
System.out.println(qry);
int z= st.executeUpdate(qry);
if(z>0)
9437100566/7205203460
JDBC : By Mr. Gitesh Kumar Mallick @ LAKSHYA 6
System.out.println("Data inserted sucessfully");
con.close();
}};
Updating a Record :
import java.sql.*;
import java.util.Scanner;
class Data3{
public static void main(String args[])throws Exception {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/college,"root","");
Statement st=con.createStatement();
Scanner s=new Scanner(System.in);
System.out.println(“enter name to update”);
String na=s.next();
System.out.println(“enter roll whose name, sem mark to be updated”);
int ro =s.nextInt();
System.out.println(“enter sem to update”);
String se = s.next();
System.out.println(“enter sem to update”);
float ma=s.nextFloat();
String qry="update student set name='"+na+"', sem='"+se+"', mark="+ma+" where roll="+ro;
System.out.println(qry);
int z= st.executeUpdate(qry);
if(z>0)
System.out.println("Data updated sucessfully");
con.close();
}};
Deleting a Record :
import java.sql.*;
import java.util.Scanner;
class Data3{
public static void main(String args[])throws Exception {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/college,"root","");
Statement st=con.createStatement();
Scanner s=new Scanner(System.in);
System.out.println(“enter roll to delete”);
int ro =s.nextInt();
String qry="delete from student where roll="+ro;
System.out.println(qry);
int z= st.executeUpdate(qry);
if(z>0)
System.out.println("Data deleted sucessfully");
con.close();
}};
9437100566/7205203460
JDBC : By Mr. Gitesh Kumar Mallick @ LAKSHYA 7
flaot ma=rs.getFloat("mark");
if(ma<30)
st.executeUpdate("update student set mark=mark+10 where roll="+ro);
}
con.close();
-----------------
When the above if condition in the while loop satisfies for the first time. The executeUpdate() method will
work ,but rs will be closed ,because con,st,rs all are references, because Connection, Statement, ResultSet are
interfaces, and interface cannot have its own object, rather it can hold/point to an object of it’s derived class . When
con getting the data from object of DriverManager, st is getting the data from con and automatically rs getting data
from st. Therefore if st will execute the executeUpdate() method then rs will never get any record from st, during
this time rs will be closed. We can adopt following mechanism to overcome this situation :
Therefore ,if we want to manipulate the database while fetching the data then we have to fetch the data
and store it in a 2D object array. After that we can iterate the object array and during this time we can manipulate
the database by executeUpdate() method.
We can also create multiple statement so that one will browse and other will update data.
Apart from the above mechanism we can use the following updatable method of ResultSet to
manipulate the data while fetching or browsing the database.
public void updateRow() :- This method update the current record pointed by ResultSet ,but value to individual
coulmn will be given by above 8 update method.
let's update mark and semester of current record.
rs.updateFloat("mark",70);
rs.updateString("sem","VIII"); similarly we can specify values for other columns then we can
update the record by :
rs.updateRow();
publicc void insertRow() :- This method will insert a new record in the current position of the ResultSet,but
values for individual fiels will be given by the above 8 methods, then we can use insertRow().
rs.updateString(“name”, “Kalia”);
rs.updateInt(“roll”, 111);
rs.updateString(“sem”, “vi”);
rs.updateFloat(“mark”,1100.0F);
rs.insertRow();
public void moveToInsertRow():- If we us this method before insertRow() method then a new record will be
9437100566/7205203460
JDBC : By Mr. Gitesh Kumar Mallick @ LAKSHYA 8
inserted at the end of all existing record.
rs.moveToInsertRow();
rs.updateString(“name”, “Kalia”);
rs.updateInt(“roll”, 111);
rs.updateString(“sem”, “vi”);
rs.updateFloat(“mark”,1100.0F);
rs.insertRow();
public void deleteRow():- It will delete the current record pointed by ResultSet.
9437100566/7205203460
JDBC : By Mr. Gitesh Kumar Mallick @ LAKSHYA 9
DriverManager class: The DriverManager class acts as an interface or a broker between user and drivers. It
keeps track of the drivers that are available and handles establishing a connection between a database and the
appropriate driver. The DriverManager class maintains a list of Driver classes that have registered themselves by
calling the method DriverManager.registerDriver().
Connection interface: A Connection is the session between java application and database. The Connection
interface is a factory of Statement, PreparedStatement, and DatabaseMetaData i.e. object of Connection can be
used to get the object of Statement and DatabaseMetaData. The Connection interface provide many methods for
transaction management like commit(),rollback() etc.
1) public Statement createStatement(): creates a statement object that can be used to execute SQL queries.
2) public Statement createStatement(int resultSetType,int resultSetConcurrency):Creates a Statement object that
will generate ResultSet objects with the given type and concurrency.
3) public void setAutoCommit(boolean status): is used to set the commit status.By default it is true.
4) public void commit(): saves the changes made since the previous commit/rollback permanent.
5) public void rollback(): Drops all changes made since the previous commit/rollback.
6) public void close(): closes the connection and Releases a JDBC resources immediately.
Statement interface : The Statement interface provides methods to execute queries with the database. The
statement interface is a factory of ResultSet i.e. it provides factory method to get the object of ResultSet.
1) public ResultSet executeQuery(String sql): is used to execute SELECT query. It returns the object of
ResultSet.
2) public int executeUpdate(String sql): is used to execute specified query, it may be create, drop, insert,
update, delete etc.
3) public boolean execute(String sql): is used to execute queries that may return multiple results.
4) public int[] executeBatch(): is used to execute batch of commands.
The protocol always remains as jdbc, because we are interacting the database from the java program. The sub-
protocol is driver specific i.e. it is depended upon the type of driver. Since we have used JdbcOdbcDriver that follows
9437100566/7205203460
JDBC : By Mr. Gitesh Kumar Mallick @ LAKSHYA 10
odbc specification, hence the sub-protocol is Odbc. But if we are using Oracle driver then the sub-protocol may be
Oracle.
The subname always refers about a driver that is a driver specific. The subname is enough to keep all the driver
information such as the name of a driver, address of driver. If we use Oracle driver (thin OCI) then the subname will
contain the address and the name of the driver.
Types of Driver:-
There are 4 types of driver used to interact with the database and they are
1. Jdbc Odbc Bridge Driver( Type - I ).
2. Partly java, partly native driver( Type - II ).
3. Intermediate Database Access Server Driver(Jdbc net driver) ( Type - III ).
4. Network Driver or pure java driver( Type - IV ).
Type-I driver:- This driver is given to us by Sun Microsystems(but SUN has made it obsolete from Java 1.8). It
translates the jdbc API call into Odbc API call. Then it will pass the Odbc API call to the odbc layer. The API and
driver have to be installed and the driver should be configured with the DSN. Each SQL statement from the java
program will undergo in several layers of interaction (steps).Hence it is slower. It is not used in platform
independent java application such as in applet, because it should be installed and configured with DSN.
Type-1 driver can interact with any DB software by specific odbc driver. The relationship between Type-1
jdbc driver and odbc driver is 1:N, because for each DB software we need separate odbc driver, hence relationship
between odbc drivers and DB software is 1:1.
All jdbc driver will be managed by DriverManager service, which is the built in service of Jdk software. It
can be activated in our java app by using java.sql.DriverManager class. Programmers register the jdbc driver with
DriverManager service from java application. Registering jdbc drivers with DriverManager service is nothing but
creating jdbc driver class object and placing that obj with DriverManagerService.
Java apps use jdbc code based persistence logic to interact with DB software and to manipulate table
data(performing cord operation).
Type-II driver:- This driver is partially written in java, partially in vendor’s specification API. It converts jdbc
call to vendor’s specific API or call. Then the vendor’s specific call (statement) will be passed to the database. The
database fetches the result and returns the result in vendor specific API to this driver. Then the driver returns the
result back to the java program in the jdbc API format. This driver faster. This driver must be installed; hence it is
not used in platform independent java application. Since it is faster, it is generally used in web server for
connection, polling, connection caching( oci driver given by oracle is type-II driver).
Type-III driver:- This driver is used to connect multiple websites with multiple clients. This driver has 2 parts
i.e. (a) Client part which is interact with client, (b) Server part which interact with server.
9437100566/7205203460
JDBC : By Mr. Gitesh Kumar Mallick @ LAKSHYA 11
The client part is written in java, wherein server part is written in native language. Generally it needs to be
installed the server part is written in native language which interact with database hence it is not used in platform
independent java application.
Type-IV Driver:- This driver is purely written in java. It has the ability to interact with the database directly.
Hence it us faster. It uses the TCP/IP protocol to make connection with the database. No need to install driver
because the address of database is generally kept with this driver. Hence it is used in platform independent java
application(thin driver given by oracle is type-IV driver).
Method Description
public void setInt(int paramIndex, int sets the integer value to the given parameter index.
value)
public void setString(int paramIndex, sets the String value to the given parameter index.
String value)
public void setFloat(int paramIndex, float sets the float value to the given parameter index.
value)
public void setDouble(int paramIndex, sets the double value to the given parameter index.
double value)
public int executeUpdate() executes the query. It is used for create, drop, insert,
update, delete etc.
import java.sql.*;
class Prepdemo {
public static void main(String args[]) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection( "jdbc:mysql://localhost/college", "root", "");
PreparedStatement st = con.prepareStatement("insert into student values(?,?,?,?)");
st.setString(1, "Ganesha");
st.setInt(2, 513);
st.setString(3, "I");
st.setFloat(4, 23.2332F);
9437100566/7205203460
JDBC : By Mr. Gitesh Kumar Mallick @ LAKSHYA 12
int z=st.executeUpdate();
if(z>0)
System.out.println("data inserted successfully");
con.close();
}};
The PreparedStement is a sub interface of the Statement interface. It can be created by the
prepareStatement() of the Connection interface.
Whenever the Statement interface executes an SQL by the executeUpdate(), then DBMS compiles the
correctness of SQL. After that it will create an execution plan, so that the execution plan will get executed on
database. If we use the same SQL for several times by providing different values (insert statement in a loop), then
for each SQL going to be executed by the Statement interface a new execution plan is created by the DBMS. Hence
it will make the execution of SQL slower.
If we use same SQL for several times by providing different values using the PreparedStaement, then the
DBMS will create execution plan only once. When the SQL will execute for the first time by the PreparedStatement
then the DBMS will create the execution plan only once and stores the plan in the cache memory allotted to DBMS,
when same SQL executes second time with different set of values then the DBMS will use the execution plan created
during 1st execution.. Hence the execution of PreparedStatement is faster compared to Statement interfce.
The bind variable in PreparedStatement is represented by ?, and it is used like a place holder for different
values. In case of Statement interface we can use normal variable to provide the value dynamically like bind
variable in PreparedStatement, but in the Statement interface will accept the value dynamically for the variables to
create SQL, whereas in case of PreparedStatement the SQL is created by bind variable without any value we can
supplied values to the bind variables after creating the SQL statement. We have to use setXXX() of the Prepared
statement. Generally the Prepared statement will execute by the execute by executeUpdate().
setXXX (int bind_var_number, YYY values )
Where XXX is wrapper class name
YYY is predefined data type value.
The 1st parameter: The bind_var_number will be 1 for 1st question mark, 2 for 2nd question mark and so on.
The 2nd parameter: The values of the bind variable must be of same data type as that of this function’s wrapper
class name.
import java.sql.*;
class Prepdemo1 {
public static void main(String args[]) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection( "jdbc:mysql://localhost/college", "root", "");
PreparedStatement st = con.prepareStatement("select * from student");
ResultSet rs=st.executeQuery();
while(rs.next())
System.out.println(rs.getString(1)+"\t"+rs.getInt(2) +"\t"+rs.getString(3)+"\t"+rs.getFloat(4));
con.close();
}}
9437100566/7205203460
JDBC : By Mr. Gitesh Kumar Mallick @ LAKSHYA 13
call stdins('laxman', 102, 'V', 654654.64);
Callable Statement:- This interface is used to call the stored procedures and functions. It is the sub
interface of the PreparedStatement. It is used to execute a plsql block such as a function or procedure from a java
program. We can have business logic on the database by the use of stored procedures and functions that will make
the performance better because these are precompiled.
Suppose you need the get the age of an employee based on the employee date of birth, you may create a function
that receives date as the input and returns age of the employee as the output.
The differences between stored procedures and functions are given below:
must not have the return type. must have the return type.
We can call functions from the procedure. Procedure cannot be called from function.
Procedure supports input and output parameters. Function supports only input parameter.
Exception handling using try/catch block can be used in Exception handling using try/catch can't be
stored procedures. used in user defined functions.
The prepareCall() method of Connection interface returns the instance of CallableStatement. Syntax is given below:
Ex:
import java.sql.* ;
import java.util.* ;
public class CallProc {
public static void main(String args[]) throws Exception {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system", "manager");
Scanner sc = new Scanner(System.in);
CallableStatement cst = con.prepareCall("Call StdIns(?,?,?,?)");
System.out.print("Enter Name"); cst.setString(1 , sc.nextLine() );
System.out.print("Enter Roll"); cst.setInt(2 , sc.nextInt() );
System.out.print("Enter Sem"); cst.setString(3 , sc.next() );
System.out.print("Enter Mark"); cst.setString(4 , sc.nextFloat() );
cst.execute();
System.out.println("procedure executed");
con.close();
}}
IN type parameter values are set using the set methods inherited from PreparedStatement. The type of all OUT
type parameters must be registered prior to executing the stored procedure; their values are retrieved after
execution via the get methods provided here.
9437100566/7205203460
JDBC : By Mr. Gitesh Kumar Mallick @ LAKSHYA 14
Creating a procedure in mysql to insert a record in student table
DELIMITER $$
$$
Example:
import java.sql.*;
class Calldemo1 {
public static void main(String args[]) throws Exception {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/college", "root", "");
CallableStatement st=con.prepareCall("call simp(?, ?, ?, ?)");
st.setString(1,"Santoshi");
st.setInt(2, 106);
st.setString(3, "VI");
st.setFloat(4, 999.32F);
int z=st.executeUpdate();
System.out.println("procedure completed successfully");
con.close();
}};
DELIMITER $$
BEGIN
DECLARE count INT;
SELECT count(*), NAME, SEM, MARK FROM STUD WHERE ROLL=B;
IF count > 0 THEN
SET a = NAME;
SET c = SEM;
SET d = MARK;
END IF;
END
$$
Example :
import java.sql.*;
9437100566/7205203460
JDBC : By Mr. Gitesh Kumar Mallick @ LAKSHYA 15
class Callable2 {
public static void main(java.lang.String[] args) {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/college", "root","");
CallableStatement cs = con.prepareCall("call ST(?, ?, ?,?)");
/* All input parameters must be set and all output parameters must be registered. */
cs.registerOutParameter(1, Types.VARCHAR);
cs.setInt(2, 104); //assume 104 is the roll no. of student table
cs.registerOutParameter(3, Types.VARCHAR);
cs.registerOutParameter(4, Types.FLOAT);
} catch (Exception e) {
System.out.println("Something failed..");
System.out.println("Reason: " + e.getMessage());
e.printStackTrace();
}
}};
In this example, we are calling the ST procedure that receives one input(i.e. roll) and returns the name, sem &
mark of the given roll number. Here, we have used the registerOutParameter method of CallableStatement
interface, that registers the output parameter with its corresponding type. It provides information to the
CallableStatement about the type of result being displayed. The Types class defines many constants such as
INTEGER, VARCHAR, FLOAT, DOUBLE, BLOB, CLOB etc.
Example :
import java.sql.*;
class Callable3 {
9437100566/7205203460
JDBC : By Mr. Gitesh Kumar Mallick @ LAKSHYA 16
public static void main(java.lang.String[] args) throws Exception {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE","system", "gitesh");
ResultSetMetaData:- The information about the data is known as metadata. This interface provides the
information about ResultSet such as the no. of columns available in Resultset, column name, column’s data type.
Method Description
public String getColumnTypeName(int index)throws it returns the column type name for the
SQLException specified index.
public String getTableName(int index)throws it returns the table name for the specified
SQLException column index.
import java.sql.*;
class MetaData1 {
public static void main(String args[]) throws Exception {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager. getConnection("jdbc:oracle:thin:@localhost:1521:xe","system",
"manager");
System.out.println("Connected...");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery( "select * from emp");
ResultSetMetaData md= rs.getMetaData();
int x = md.getColumnCount();
for( int i = 1 ; i <= x; i++)
System.out.println(md.getColumnName(i) + "\t" +md.getColumnTypeName(i) );
con.close();
9437100566/7205203460
JDBC : By Mr. Gitesh Kumar Mallick @ LAKSHYA 17
}} ;
DatabaseMetaData interface: DatabaseMetaData interface provides methods to get meta data of a database
such as database product name, database product version, driver name, name of total number of tables, name
of total number of views etc.
public String getDriverName()throws SQLException: it returns the name of the JDBC driver.
public String getDriverVersion()throws SQLException: it returns the version number of the JDBC driver.
public String getUserName()throws SQLException: it returns the username of the database.
public String getDatabaseProductName()throws SQLException: it returns the product name of the
database.
public String getDatabaseProductVersion()throws SQLException: it returns the product version of the
database.
public ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern, String[]
types)throws SQLException: it returns the description of the tables of the specified catalog. The table
type can be TABLE, VIEW, ALIAS, SYSTEM TABLE, SYNONYM etc.
import java.sql.*;
class Dbmd{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system", "manager");
DatabaseMetaData dbmd=con.getMetaData();
}}
DatabaseMetaData interface that prints total number of tables :
import java.sql.*;
class Dbmd2{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection( "jdbc:oracle:thin:@localhost:1521:xe", "system","manager");
DatabaseMetaData dbmd=con.getMetaData();
String table[]={"TABLE"};
ResultSet rs=dbmd.getTables(null,null,null,table);
while(rs.next()){
System.out.println(rs.getString(3));
}
con.close();
}catch(Exception e){ System.out.println(e);}
}}
9437100566/7205203460
JDBC : By Mr. Gitesh Kumar Mallick @ LAKSHYA 18
Storing image in Oracle database : We can store images in the database in java by the help
of PreparedStatement interface. The setBinaryStream() method of PreparedStatement is used to set Binary
information into the parameterIndex.
For storing image into the database, BLOB (Binary Large Object) datatype is used in the table.
CREATE TABLE IMGTABLE (
NAME VARCHAR2(40),
PHOTO BLOB
)
Let's write the jdbc code to store the image in the database. Here we are using aa.jpg which is available in the same
location where the program is stored. You can change it according to the image location.
import java.sql.*;
import java.io.*;
public class InsertImage {
public static void main(String[] args) {
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system", "manager");
PreparedStatement ps=con.prepareStatement("insert into imgtable values(?,?)");
ps.setString(1,"soma");
con.close();
}catch (Exception e) {e.printStackTrace();}
}}
If you select the table, record is stored in the database but image will not be shown.
9437100566/7205203460
JDBC : By Mr. Gitesh Kumar Mallick @ LAKSHYA 19
Example to retrieve image from Oracle database : By the help of PreparedStatement we can retrieve
and store the image in the database. The getBlob() method of PreparedStatement is used to get Binary
information, it returns the instance of Blob. After calling the getBytes() method on the blob object, we can get the
array of binary information that can be written into the image file.
Now let's write the code to retrieve the image from the database and write it into the directory so that it can be
displayed. In AWT, it can be displayed by the Toolkit class. In servlet, jsp, or html it can be displayed by the img
tag.
import java.sql.*;
import java.io.*;
public class RetrieveImage {
public static void main(String[] args) {
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system", "manager");
fout.close();
}//end of if
System.out.println("ok");
con.close();
}catch (Exception e) {e.printStackTrace(); }
}}
Example to store file in Oracle database: The setCharacterStream() method of PreparedStatement is used to
set character information into the parameterIndex.
For storing file into the database, CLOB (Character Large Object) datatype is used in the table.
import java.io.*;
import java.sql.*;
public class StoreFile {
9437100566/7205203460
JDBC : By Mr. Gitesh Kumar Mallick @ LAKSHYA 20
public static void main(String[] args) {
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","manager");
PreparedStatement ps=con.prepareStatement("insert into filetable values(?,?)");
ps.setInt(1,101);
ps.setCharacterStream(2,fr,(int)f.length());
int i=ps.executeUpdate();
System.out.println(i+" records affected");
con.close();
}catch (Exception e) {e.printStackTrace();}
}}
Example to retrieve file from Oracle database: The getClob() method of PreparedStatement is used to get
file information from the database.
The example to retrieve the file from the Oracle database is given below.
import java.io.*;
import java.sql.*;
Clob c=rs.getClob(2);
Reader r=c.getCharacterStream();
int i;
while((i=r.read())!=-1)
fw.write((char)i);
fw.close();
con.close();
System.out.println("success");
}catch (Exception e) {e.printStackTrace(); }
}}
9437100566/7205203460
JDBC : By Mr. Gitesh Kumar Mallick @ LAKSHYA 21
Transaction Management:- The transaction management means the entire job on the database must remain
atomic i.e. the transaction should be atomic. A transaction will become atomic if it allows us to perform all the
transaction i.e. SQL statement to execute once.
By default, all the SQL statement in java are auto commit. To achieve the transaction management, we have to
make the autocommit functionality or SQL statements as false by using the followings method of the Connection
interface.
Transaction represents a single unit of work. The ACID properties describes the transaction management well.
ACID stands for Atomicity, Consistency, isolation and durability. Atomicity means either all successful or none.
Consistency ensures bringing the database from one consistent state to another consistent state.
Isolation ensures that transaction is isolated from other transaction. Durability means once a transaction has
been committed, it will remain so, even in the event of errors, power loss etc.
Method Description
import java.sql.*;
import java.util.*;
class Trans {
public static void main(String args[]) throws Exception {
Connection con=null;
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
con=DriverManager.getConnection("jdbc:mysql://localhost/college", "root" , "");
Statement st = con.createStatement();
Scanner s =new Scanner(System.in);
con.setAutoCommit(false);
for(int i=0;i<2;i++) {
System.out.println("Enter name");
String na=s.next();
System.out.println("Enter roll");
int ro=s.nextInt();
System.out.println("Enter sem");
String se=s.next();
System.out.println("Enter mark");
float ma=s.nextFloat();
String qry="insert into student values('"+na+"', "+ro+",'"+se+"', "+ma+")";
System.out.println(qry);
9437100566/7205203460
JDBC : By Mr. Gitesh Kumar Mallick @ LAKSHYA 22
st.executeUpdate(qry);
}
System.out.println("Enter roll to update");
int r=s.nextInt();
System.out.println("Enter mark to update");
float m=s.nextFloat();
st.executeUpdate("update student set mark = "+m+" where roll="+r);
System.out.println("Mark updated sucessfully");
con.commit();
}catch(Exception e){
try{
con.rollback();
}catch(Exception ee){ }
System.out.println(e);
}
try{
con.close();
}catch(Exception ee){ }
}};
import java.sql.*;
class Ins {
public static void main(String args[]) throws Exception {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con=DriverManager.getConnection("jdbc:mysql://localhost/college", "root" , "");
Statement st = con.createStatement();
for(int i=400, j=65; i<426 ; i++, j++){
String qry="insert into student values('"+ (char)j+"', "+i+", 'vii', "+ (i*10) +")";
st.addBatch(qry);
}
st.executeBatch();
con.close();
}};
JDBC RowSet : The instance of RowSet is the java bean component because it has properties and java bean
notification mechanism. It is introduced since JDK 5. It is the wrapper of ResultSet. It holds tabular data like
ResultSet but it is easy and flexible to use.
9437100566/7205203460
JDBC : By Mr. Gitesh Kumar Mallick @ LAKSHYA 23
The implementation classes of RowSet interface are as follows:
JdbcRowSet
CachedRowSet
WebRowSet
JoinRowSet
FilteredRowSet
import java.sql.*;
import javax.sql.RowSetEvent;
import javax.sql.RowSetListener;
import javax.sql.rowset.JdbcRowSet;
import javax.sql.rowset.RowSetProvider;
while (rowSet.next()) {
// Generating cursor Moved event
System.out.println("Name: " + rowSet.getString(1));
System.out.println("Roll: " + rowSet.getInt(2));
System.out.println("Sem: " + rowSet.getString(3));
System.out.println("Sem: " + rowSet.getFloat(4));
}
}}
9437100566/7205203460
JDBC : By Mr. Gitesh Kumar Mallick @ LAKSHYA 24
Full example of Jdbc RowSet with event handling : To perform event handling with JdbcRowSet, you
need to add the instance ofRowSetListener in the addRowSetListener method of JdbcRowSet.
The RowSetListener interface provides 3 method that must be implemented. They are as follows:
Let's write the code to retrieve the data and perform some additional tasks while cursor is moved, cursor is changed
or rowset is changed. The event handling operation can't be performed using ResultSet so it is preferred now.
import java.sql.*;
import javax.sql.RowSetEvent;
import javax.sql.RowSetListener;
import javax.sql.rowset.JdbcRowSet;
import javax.sql.rowset.RowSetProvider;
while (rowSet.next()) {
// Generating cursor Moved event
System.out.println("Name: " + rowSet.getString(1));
System.out.println("Roll: " + rowSet.getInt(2));
System.out.println("Sem: " + rowSet.getString(3));
System.out.println("Sem: " + rowSet.getFloat(4));
}
}}
9437100566/7205203460
JDBC : By Mr. Gitesh Kumar Mallick @ LAKSHYA 25
Create an excel sheet store it as Book1.xlsx and store it under d:/datas folder. Create a table in Sheet1 or Sheet2
whatever you like.
import java.sql.*;
//Please see Connecting to the Database section of Chapter 2. Installation in Development Document
//Please change "demodata" to your database directory
String url = "jdbc:Excel:///D:/datas/Book1.xlsx";
ResultSet rs = stmt.executeQuery(sql);
Object colval;
while (rs.next()) {
for (int i = 1; i <= iNumCols; i++) {
colval = rs.getObject(i);
System.out.print(colval + " ");
}
System.out.println();
}
rs.close();
stmt.close();
con.close();
}
catch (Exception e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
}
--> store the file with .java extn
--> copy the Excel_JDBC30.jar to the same location where this program is stored.
9437100566/7205203460
JDBC : By Mr. Gitesh Kumar Mallick @ LAKSHYA 26
Answer : This question is not directly related to JDBC but some time asked during JDBC interviews. Cold back is the
backup techniques in which backup of files are taken before the database restarted. In hot backup backup of files
and table is taken at the same time when database is running. A warm is a recovery technique where all the tables
are locked and users cannot access at the time of backing up data.
Optimistic Locking: optimistic locking lock the record only when update take place. Optimistic locking does not use
exclusive locks when reading
Pessimistic locking: in this record are locked as it selects the row to update
9437100566/7205203460