Jdbcnotes
Jdbcnotes
-----------------------------
JDBC:
-----
In Enterprise applications, it is convention to manage the details of the
enterprises like Employee details, Customers details, Products Details, Services
details, clients details,..... To Manage these details we have to use Storage Areas
in Enterprise applications.
Q)To manage data permanently we have already File Systems then what is the
rquirement to use Database Management Systems?
--------------------------------------------------------------------
Ans:
-----
1. File Systems are managed by the local Operating Systems , it is platform
dependent, it is not suitable for the platform Independent Programming Languages
like Java.
DBMS are platform independent, they are very much suitable for the platform
independent Programming languages like Java.
5. File Systems are not having Query Languages Support, so database operations are
very much difficult.
DBMS is able to have Query Languages support, it is very simple to perform database
operations.
Q)To manage the data we have already DBMS then what is the requirement to use
Datawarehouses?
---------------------------------------------------------------------
Ans:
-----
1. DBMS are able to store less data when compared with Datawarehouses.
2. DBMS is very good while performing the operations like insert, update,
delete,... , but, it is not good while performing retrieval operations.
Q)What are the differences between Database and Database Management Systems?
---------------------------------------------------------------------
Ans:
-----
1. Database is a memory Unit, it able to store data.
DBMS is the collection of inter related data and a set of programs to perform
database operations like insert, update, select, delete,...
In general, there are more no of database management systems, but, we will use the
following three Database Management systems .
--> At Databases, Database Engines are able to execute sql queries by following the
following phases.
1. Query Tokenization
2. Query Parsing
3. Query Optimization
4. Query Execution
1. Query Tokenization:
--> It able to devide the complete sql query into no of pieces, where each and
every piece is called as a Token, finally, Query Tokenization phase is able to gete
stream of Tokens as an output.
2. Query Parsing:
--> The main intention of Query Parsing Phase is to check whether
the provided sql query contains errors or not.
--> Query Parsing phase will take stream of tokens as an input from
Query Tokenization Phase, it is trying to construct a tree with the tokens
called as "Query Tree".
--> If Query Tree is constructoed Successfully then there are no
errors in the provided sql query.
--> If Query is not constructed Successfully then there are some
syntax errors in the provided SQL query.
3. Query Optimization:
--> It will take Query Tree as an input, it will apply no of Query
Optimization mechanisms , it will generate Optimized Query Tree.
--> The main intention of Query Optimization phase is to generate
Optimized Query Tree inorder to reduce execution time and inorder to reduce
memory utilization.
4. Query Execution:
--> It will take Optimized query tree as an input, it will execute
that optimized Query Tree bby having an interpretor internally and it will
perfrom the required database operation and it will send the result of the Database
operation to the respective Client, that is CMD.
Def2: JDBC is a Technology, not a Programming Language , it will provide very good
environment to connect with database from Java applications inorder to perform
database operations from Java applications.
In Jdbc applications, when we submit database logic from Java application database,
at database, database Engine has to execute Database logic,p but, database Engine
will not execute the provided database logic, because, database Engine is unable to
understand Java representations, it able to understand Query Languages
representations.
In the above context, what ever the translator we have taken to convert Java
representations to Dabase representations and database representations to Java
representations that convertor is called as "Driver".
As per the above convention, all the Database vendors have provided their own
implementation classes for the java.sql.Driver interface in their respective
Databases.
In general, for each and every database a seperate driver implementation was
provided , but, all these drivers are devided into the following five types.
1. Type-1 Driver
2. Type-2 Driver
3. Type-3 Driver
4. Typr-4 Driver
5. Type-5 Driver
1. Type-1 Driver:
-----------------
--> java.sql.Driver is an interface provided by SUN Microsystems and its
implementation classes are provided by all the database vendors, here when Database
vendors wants provide implementation for Driver interface, all Database vendors
have requested to SUN Microsystems about to provide a reference implementation or a
model implementation or a showcase for Driver interface.
--> As per the request from all database vendors , SUN Microsystems
has provided a reference implementation for java.sql.Driver interface in the
from of "sun.jdbc.odbc.JdbcOdbcDriver", here SUN Microsystems provided Driver
"sun.jdbc.odbc.JdbcOdbcDriver" is treated as "Type-1 Driver".
2. Type-2 Driver
----------------
--> Type-2 Driver is also called as "Part Java, Part Native Driver" or
simply "Native Driver".
--> Type-2 Driver is faster Driver when compared with Type-1 Driver,
because, it does not required two times conversions to interact with database.
--> Type-2 Driver is more Portable Driver when compared with Type-1
Driver, because, it is not dependenct on the Microsoft product ODBC driver.
3. Type-3 Driver
------------------
--> Type-3 Driver is also called as "Middleware Database Server Access
Driver" or simply "Network Driver".
--> Type-1 Driver and Type-2 Drivers are suggestible for Standalone
applications, but, Type-3 Driver is for only Web applications and Distributed
applications, it is not suitable for Standalone applications.
--> Type-3 Driver is more portable Driver when compared with Type-1
Driver and Type-2 Driver, because, It is not dependent on the Microsoft product
ODBC Driver and the Database Vendor provided native library.
--> Type-3 Driver is faster driver when compared with Type-1 and
Type-2 Drivers, becausem it will not take two times conversions to interact
with database from java application and it will not require to wait to load the
Database vendor provided native library, it require Database IP Address and Port
NUmber to interact with database.
4. Typr-4 Driver:
-----------------
--> Type-4 driver is also called as "Pure Java Driver" or simply
"Thin Driver".
--> When compared with Type-1, Type-2, Type-3 Drivers, Type-4 Driver
is more Portable Driver, because, it is not dependent on the Microsoft product
ODBC Driver, not dependenct on the Database Vendor Provided Native Library, not
dependent on the application Server.
--> Type-4 Driver is Faster Driver, becasue, it does not required two
times conventions , it does not required to load Database vendor provided
native library and it does not required to start application server.
--> Type-4 driver will provide more performance when compared with
Type-1 Driver, Type-2 Driver and Type-3 Driver.
--> Type-4 driver is light weight driver and most economical driver.
Type-5 Driver:
---------------
--> Type-5 Driver was not provided by SN Microsystems / Oracle Corp, Type-5 Driver
was provided a third party vendor "Progress Data Direct" Company.
--> Type-4 Driver provided almost all 15 to 18 years back, mean while, no of new
technologies are arrived, no of enhancements are are available on the existed
technologies, no of ORM implementations are coming, for all these enhancements, new
technologies Type-4 Driver is not providing service effectivily.
To overcome all these problems, Progress Data Direct has provided a new type of
Driver for Jdbc that is Type-5 Driver.
--> If we use Type-4 Driver in application servers and if no of users are increased
, automatically, it unable to provide its functionalities effectivily for the all
the users, it will provide performance issues.
--> Due to the above reasons, Type-4 Driver is not providing solutions for
Scalability.
2. Resource Utilization:
---> In general, Type-4 Driver required more no of CPU cycles to perform its
functanalities, it will increase application execution time, it will reduce
application performance.
4. Complex Deployment:
---> If we use Oracle10g/10xe for our applications thyen we have to use ojdbc14.jar
inorder to get Type-4 Driver.
---> If we use Oracle11g/11xe for our applications then we have to use ojdbc6.jar
file inorder to get Type-4 Driver.
---> If we use Oracle12c for our applications then we have to use ojdbc7.jar file
iorder to get Type-4 driver.
1. Unrestricted Performance:
-----------------------------
--> Even if we deploy Type-5 Driver in multiple JVMs and in application Server ,
when no of users are increased to access type-5 Driver, then , Type-5 driver is not
providing down performance, it will provide very good for the applications, Type-5
Driver is able to provide solution for "Scalability" problem.
2. Codeless Configurations
--------------------------
Type-5 Driver will add , Configure or tune for any application inorder to provide
its functionalities and behaviours with out changing application code.
3. Resource Effeciency
------------------------
--> Type-5 Drver does not required more no of CPU cycles, it will take less memory
and less execution time, it will provide more performance to the applications.
5. Streamlined Standardization
--------------------------------
--> Type-5 Driver is not giving any option for the developers about to use Vendor
Specific Code in our applications, So it follows Streamlined Standardization.
Steps to prepare JDBC Applications:
-----------------------------------
1. Download and Install Database Software[Oracle/MySQL]
2. Download and Install IDE[Eclipse/IntelliJ]
3. In Eclipse IDE, prepare Java project and prepare JDBC
Program
Note: We must have Java Softwares in Our System[JDK7 and
JDK8 and above]
To prepare JDBC program we have to use the following steps.
1. Load and Register Driver
2. Establish Connection between Java application and Database
3. Create either Statement or PreparedStatement or
CallableStatement.
4. Write and Execute SQL Queries
5. Close the resources like Connection, Statement,....
From all the above steps, the steps like 1,2,3 and 5 are repeatable for all the
JDBC applications, but, 'Write and execute SQL queries' step is varied from
application to application, due to this reason, Steps1,2,3 and 5 are called as
'Boilerplate Code'.
--> If we want to 'Load and Refister Driver' in Jdbc applications, first, we have
to make available driver class to Jdbc application or we have to give an
informastion to JVM where Driver class .class file is existed, to do this, we have
to set 'classpath' environment variable.
set classpath=C:\Oracle18xe\dbhomeXE\jdbc\lib\ojdbc8.jar;
Note: If we use IDEs to prepare Jdbc applications then we have to set driver jar
file in Project library.
--> If we use Type-1 Driver in Jdbc applications then it is not requird to set
classpath environment variable and it is not required to keep any jar file under
project library, because, Type-1 driver class was provided by SUN Microsystems in
the same Java Software.
--> If we want to use Type-1 Driver in Jdbc applications then we have to configure
the Microsoft product ODBC driver in our system, because, Type-1 driver is
interdependent on the Microsoft product ODBC driver.
Note: Type-1 Driver is available in Java upto JAVA7 version only, it is not
available from JAVA8 version .
After getting Driver class in Jdbc applications, we have to load and register
driver class in Jdbc applications, for this, we have to use the following method
from java.lang.Class.
When JVM executes the above instructions, JVM will perform the following actions.
1)JVM will take the provided Driver class from forName() method.
2)JVM will search for the driver class's .class file at the
following locations.
a)At current location from where we are executing appl.
b)At Java predefined library.
c)At the locations refered by 'classpath' env variable.
3)If the requird Driver .class file is not existed at all the
above locations then JVM will raise an Exception like
"java.lang.ClassNotFoundException".
4)If the required Driver .class file is existed at either of the
above locations then JVM will load driver class bytecode to the memory.
5)At the time of loading Driver class bytecode to the memory, JVM
will execute a 'static block' and JVM will execute
DriverManager.registerDriver() method as part of the static block execution.
6)By the execution of 'DriverManager.registerDriver()' method only
Jdbc Driver will be registerd with our application.
class JdbcApp{
public static void main(String[] args)throws Exception{
//Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Class.forName("oracle.jdbc.OracleDriver");
}
}
java.sql.Driver [I]
java.sql.DriverManager [C]
java.sql.Connection [I]
java.sql.Statement [I]
java.sql.PreparedStatement [I]
java.sql.CallableStatement [I]
java.sql.ResultSet [I]
java.sql.ResultSetMetaData [I]
java.sql.DatabaseMetaData [I]
-------
-------
Where dbUserName and dbPassword are the database details which we provided at
the time of Database installation.
Note: In My Oracle18XE Database installation we have given
dbUserName : system
dbPassword : durga
Where driverURL is varied from driver to driver but its format is fixed.
MainProtocolName:SubProtocolName:DBName
Type-1[SUN] : jdbc:odbc:nag[dsnName]
Type-4[Oracle]: jdbc:oracle:thin:@localhost:1521:xe
Type-4[MySQL] : jdbc:mysql://localhost:3306/dbName
EX:
Connection con = DriverManager.getConnection("jdbc:odbc:nag",
"system","durga");
When JVM executes the above instructions, JVM will perform the following actions.
In the above context, getConnection() method has created object for the
impelmentation class of java.sql.Connection which was provided by the respective
database vendor.
java.sql.Statement
java.sql.PreparedStatement
java.sql.CallableStatement
Statement st = con.createStatement();
-----
-----
}
}
--> In Jdbc applications, executeQuery() method can be used to execute 'select' sql
queries inorder to fetch data from Database table.
--> In Jdbc applications, executeUpdate() method can be used to execute non select
sql queries inorder to perform the database operations like create table, inserting
records, updating table, deleting records, alter table and drop table.
--> In Jdbc applications, execute() method can be used to execute both the types of
SQL queries like select and non select sql queries inorder to perfrom all the
database operations.
Note: If we know the sql query in advance which we want to execute there we will
use either executeQuery() and executeUpdate() method, but, if we dont know the sql
query which we want to execute in advance there we will use 'execute() method'.
When we access executeQuery() method 'select' sql query then JVM will perform the
following actions.
1. JVM will submit the provided 'select' sql query to JdbcOdbcDriver
2. JDBC-OdbcDriver will send that sql query to Connection.
3. Connection will carry select sql query to ODBC driver.
4. ODBC Driver will send select sql query to Database Engine.
5. DBE will execute select sql query by performing Query
Tokenization, Query Parsing, Query Optimization and Query Execution .
6. By the execution of sql query, Database Engine will fetch data
from Database table and Database Engine send fetched data to Java application
throigh ODBC Driver, Connection and JdbcOdbcDriver.
7. At Java application, fetched data will be stored in the form of
an object called as"ResultSet" Object.
8. The generated ResultSet object reference value will be returned
by executeQuery() method.
When we access executeUpdate() method with 'non select query' then JVM will perfrom
the following actions.
1. JVM will take the provided Non sql query from executeUpdate()
method.
2. JVM will send the provided Non Select Sql query to Database
Engine through Jdbc Driver and Connection.
3. At Database, Database Engine will execute Non Select Sql query
and perfroms manipulations on no of records and identifies the rowCount value
that is the no of records which are effected with the provided sql query.
4. Database Engine will send the generated RowCount value back to
Java application through Jdbc Driver and Connection.
5. At Java application, the generated RowCount value will be
returned from executeUpdate() method.
In Jdbc applications, execute() method can be used to execute both Select and Non
Select sql queries.
In Jdbc applications, if we execute slect sql query with execute() method then JVM
will send that select sql query to database Engine, where Database Engine will
fetch the data from Database and Send back to Java application in the form of
ResultSet object, but, execute() method will return 'true' as boolean value.
boolean b = st.execute("select * from emp1");
Sopln(b);// true
In Jdbc applications, if we execute non select sql query with execute() method then
JVM will send non select sql query to Database Engine, where Database Engine will
perfrom the respective database operations and Database Engine will return the
generated RowCount to Java application, but, execute() method will return only
'false' as boolean value.
To close the rehsources we have to use the following methods from Statement,
ResultSet, Connection,...
Application-1:
---------------
Driver: Type-1 Driver
Java Version: JAVA7 version
System Conf: ODBC Configuration[DSN Name: nag]
DriverClassName: sun.jdbc.odbc.JdbcOdbcDriver
Driver URL : jdbc:odbc:dsnName[nag]
DB Operation : create table with the name 'emp1' and with the
columns ENO[PK], ENAME, ESAL, EADDR
EX:
----
package com.durgasoft.app01.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
//Create Statement
Statement st = con.createStatement();
Application-2:
---------------
Driver : Type-1 Driver
Driver ClassName: sun.jdbc.odbc.JdbcOdbcDriver
Driver URL : jdbc:odbc:dsnName[nag]
EX:
----
package com.durgasoft.app02.test;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
Application-3:
---------------
Driver : Type-1 Driver
Driver ClassName: sun.jdbc.odbc.JdbcOdbcDriver
Driver URL : jdbc:odbc:dsnName[nag]
EX:
----
package com.durgasoft.app03.test;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
while(true) {
System.out.println();
System.out.print("Column Name : ");
String colName = br.readLine();
System.out.print("Column Data Type : ");
String colDataType = br.readLine();
System.out.print("Column Size : ");
int colSize = Integer.parseInt(br.readLine());
}
//System.out.println(query);
st.executeUpdate(query);
System.out.println("Table "+tname+" Created Successfully");
br.close();
st.close();
con.close();
}
}
1. Declare all the resources with null values before try block.
2. Create the resources inside try block.
3. Close the resources in finally block.
class Test{
public static void main(String[] args){
BufferedReader br = null;
Connection con = null;
Statement st = null;
ResultSet rs = null;
try{
------
br = new BufferedReader(new InputStreamReader(System.in));
con = DriverManager.getConnection(--,--,--);
st = con.createStatement();
-----
}catch(Exception e){
e.printStackTrace();
}finally{
try{
br.close();
st.close();
con.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
}
Application-4:
--------------
Driver : Type-1 Driver
Driver ClassName: sun.jdbc.odbc.JdbcOdbcDriver
Driver URL : jdbc:odbc:dsnName[nag]
Java Version: Java7 version.
eno = 111
ename = AAA
esal = 5000
eaddr = Hyd
EX:
----
package com.durgasoft.app04.test;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
try {
//Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:nag", "system",
"durga");
st = con.createStatement();
br = new BufferedReader(new InputStreamReader(System.in));
while(true) {
System.out.print("Employee Number : ");
int eno = Integer.parseInt(br.readLine());
System.out.print("Employee Name : ");
String ename = br.readLine();
System.out.print("Employee Salary : ");
float esal = Float.parseFloat(br.readLine());
System.out.print("Employee Address : ");
String eaddr = br.readLine();
Application-5
---------------
Driver : Type-1 Driver
Driver ClassName: sun.jdbc.odbc.JdbcOdbcDriver
Driver URL : jdbc:odbc:dsnName[nag]
Java Version: Java7 version.
update emp1 set ESAL = ESAL + 500 where ESAL < 10000
EX:
----
package com.durgasoft.app05.test;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
try {
//Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:nag", "system",
"durga");
st = con.createStatement();
br = new BufferedReader(new InputStreamReader(System.in));
Application-6
---------------
Driver : Type-1 Driver
Driver ClassName: sun.jdbc.odbc.JdbcOdbcDriver
Driver URL : jdbc:odbc:dsnName[nag]
Java Version: Java7 version.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:nag", "system",
"durga");
st = con.createStatement();
br = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Salary Range : ");
float salRange = Float.parseFloat(br.readLine());
int rowCount = st.executeUpdate("delete from emp1 where ESAL <
"+salRange);
System.out.println("No Of Employees Deleted : "+rowCount);
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
br.close();
//st.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Application-7
---------------
Driver : Type-1 Driver
Driver ClassName: sun.jdbc.odbc.JdbcOdbcDriver
Driver URL : jdbc:odbc:dsnName[nag]
Java Version: Java7 version.
EX:
----
package com.durgasoft.app07.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
try {
//Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:nag", "system",
"durga");
st = con.createStatement();
st.executeUpdate("drop table emp3");
System.out.println("Table emp3 dropped Successfully");
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
st.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
ResultSet:
----------
In Jdbc applications, when we execute 'select' sql query with executeQuery(), JVM
will send the provided select sql query to Database ENgine through JUdbc Driver and
Connection, where ar database, Database Engin will execute that provided select sql
query , it will fetch data from database and it will send the fetched data to Jdbc
application in the form of ResultSet object.
ResultSet is an object in Jdbc, it able to manage or store the fetched data from
Database table when we execute select sql query.
To read data from ResultSet object, we have to use the following steps for each and
record.
1. Check whether next record is existed or not from the current cursor
position, for this, we have to use the following method.
2. After getting cursor to the current record then read columns data
individually, for this, we have to use the following7 method.
Repeate the above two steps for all the records of the ResultSet.
Application-8
---------------
Driver : Type-1 Driver
Driver ClassName: sun.jdbc.odbc.JdbcOdbcDriver
Driver URL : jdbc:odbc:dsnName[nag]
Java Version: Java7 version.
EX:
----
package com.durgasoft.app08.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
try {
//Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:nag", "system",
"durga");
st = con.createStatement();
rs = st.executeQuery("select * from emp1");
System.out.println("ENO\tENAME\tESAL\tEADDR");
System.out.println("------------------------------");
while(rs.next()) {
System.out.print(rs.getInt(1)+"\t");
System.out.print(rs.getString(2)+"\t");
System.out.print(rs.getFloat(3)+"\t");
System.out.print(rs.getString(4)+"\n");
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
rs.close();
st.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
'C:\Oracle18xe\dbhomeXE\jdbc\lib\ojdbc8.jar'
If we are preparing jdbc application with out IDE then we have to set 'classpath'
env variable to ojdbc8.jar file.
set classpath=C:\Oracle18xe\dbhomeXE\jdbc\lib\ojdbc8.jar;
If we use Eclipse IDE then we have to add ojdbc8.jar file in Project Library.
EX:
----
package com.durgasoft.app09.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
try {
Class.forName("oracle.jdbc.OracleDriver");
con = DriverManager.getConnection("jdbc:oracle:oci8:@xe",
"system", "durga");
st = con.createStatement();
rs = st.executeQuery("select * from emp1");
System.out.println("ENO\tENAME\tESAL\tEADDR");
System.out.println("----------------------------");
while(rs.next()) {
System.out.print(rs.getInt("ENO")+"\t");
System.out.print(rs.getString("ENAME")+"\t");
System.out.print(rs.getFloat("ESAL")+"\t");
System.out.print(rs.getString("EADDR")+"\n");
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
rs.close();
st.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
We need middleware component from Applications or we have to use some proxy Server
by IDSServer,
Type-3 Driver :
-----------------
1)Download and Install IDSServer[www.idssoftware.com]
2)Download and Install Oracle11xe 32 bit.
3)Create System DSN Name in Our System for Oracle XE.[nagdsn]
4)Download and Install any JDK with 32 bit.[OpenJDk1.8]
EX:
----
package com.durgasoft.app10.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
try {
Class.forName("ids.sql.IDSDriver");
con = DriverManager.getConnection("jdbc:ids://localhost:12/conn?
dsn=nagdsn", "system", "durga");
st = con.createStatement();
rs = st.executeQuery("select * from emp1");
System.out.println("ENO\tENAME\tESAL\tEADDR");
System.out.println("------------------------------");
while(rs.next()) {
System.out.print(rs.getInt("ENO")+"\t");
System.out.print(rs.getString("ENAME")+"\t");
System.out.print(rs.getFloat("ESAL")+"\t");
System.out.print(rs.getString("EADDR")+"\n");
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
//rs.close();
//st.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Type-4 Driver:
---------------
Driver Class Name : oracle.jdbc.OracleDriver[from Oracle9i version]
oracle.jdbc.driver.OracleDriver[Outdated].
Driver URL : jdbc:oracle:thin:@localhost:1521:xe [OracleXX_XE]
jdbc:oracle:thin:@localhost:1521:ORCL[OracleXX_G]
Oracle Software has provided all these JAR files in the following locations.
'C:\Oracle18xe\product\18.0.0\dbhomeXE\jdbc\lib'
If we prepare JDBC application with out using IDE then we have to set classpath
environment variable to these JAR files.
set classpath=C:\Oracle18xe\product\18.0.0\dbhomeXE\jdbc\lib\ojdbc8.jar
If we use IDEs like Eclipse then we have to keep ojdbc8.jar file in project
library.
EX:
---
package com.durgasoft.app11.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
try {
Class.forName("oracle.jdbc.OracleDriver");
con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system",
"durga");
st = con.createStatement();
rs = st.executeQuery("select * from emp1");
System.out.println("ENO\tENAME\tESAL\tEADDR");
System.out.println("-----------------------------");
while(rs.next()) {
System.out.print(rs.getInt("ENO")+"\t");
System.out.print(rs.getString("ENAME")+"\t");
System.out.print(rs.getFloat("ESAL")+"\t");
System.out.print(rs.getString("EADDR")+"\n");
}
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Type-5:
---------
If we want to use Type-5 Driver we have to Download and install Type-5 Driver in
our System from www.progress.com/jdbc.
If we prepare JDBC application with out the IDEs then we have to set classpath
environment variable to 'C:\Progress\DataDirect\JDBC_60\lib\oracle.jar'.
If we use the IDEs like Eclipse IDE then we have to keep oracle.jar file in Project
Library.
EX:
----
package com.durgasoft.app12.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
try {
Class.forName("com.ddtek.jdbc.oracle.OracleDriver");
con =
DriverManager.getConnection("jdbc:datadirect:oracle://localhost:1521;ServiceName=XE
", "system", "durga");
st = con.createStatement();
rs = st.executeQuery("select * from emp1");
System.out.println("ENO\tENAME\tESAL\tEADDR");
System.out.println("-------------------------------");
while(rs.next()) {
System.out.print(rs.getInt("ENO")+"\t");
System.out.print(rs.getString("ENAME")+"\t");
System.out.print(rs.getFloat("ESAL")+"\t");
System.out.print(rs.getString("EADDR")+"\n");
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
rs.close();
st.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
MetaData in Jdbc:
------------------
--> Data about the data is called as MetaData.
--> There are two types of MetaData in JDBC.
1. Database MetaData
2. ResultSet MetaData
1. Database MetaData:
-----------------------
--> Data about the database is called as Database MetaData , where
Database Metadata includes Name of the Database, Database version details,
Database Supported SQL keywords, Database Supported Numeric Functions, Database
Supported String Functions, Is Database supports StoredProcedured and Functions, Is
Database supports Batch Updations,........
--> To get Name of the Database we have to use the following method.
public String getDatabaseProductName()
--> To get Driver Major Version we have to use the following method
public int getDriverMajorVersion()
--> To get Driver Minor Version we have to use the following method.
public int getDriverMinorVersion()
--> To get all Supported SQL Keywords we have to use the following
method.
public String getSQLKeywords()
------
-------
EX:
----
package com.durgasoft.app13.test;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
try {
Class.forName("oracle.jdbc.OracleDriver");
con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system",
"durga");
md = con.getMetaData();
System.out.println(md.getDatabaseProductName());
System.out.println(md.getDatabaseProductVersion());
System.out.println(md.getDriverMinorVersion());
System.out.println(md.getDriverMajorVersion());
System.out.println(md.getSQLKeywords());
System.out.println(md.getNumericFunctions());
System.out.println(md.getStringFunctions());
System.out.println(md.supportsStoredProcedures());
System.out.println(md.supportsBatchUpdates());
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Note: When we want to work with an unknown database , there, to get some details
about the database there we will use "DatabaseMetaData".
2. ResultSetMetaData:
----------------------
--> Data about the ResultSet is called as ResultSetMetaData.
--> In Jdbc applications, ResultSetMetaData includes the details
about the ResultSet object like no of columns which are existed in ResultSet
object, Column Names, Column data Types, Column Sizes,.....
--> In Jdbc applications, to represent ResultSetMetaData object, JDBC
API has provided a predefined interface in the from of
'java.sql.ResultSetMetaData'.
--> In general, we will use ResultSetMetaData when we want to work
with an unknown database table and when we want to get details of a particular
database table.
EX:
---
package com.durgasoft.app14.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
try {
Class.forName("oracle.jdbc.OracleDriver");
con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system",
"durga");
st = con.createStatement();
rs = st.executeQuery("select * from emp1");
ResultSetMetaData md = rs.getMetaData();
int columnCount = md.getColumnCount();
System.out.println("No Of Coumns : "+columnCount);
System.out.println();
for(int columnIndex = 1; columnIndex <= columnCount; columnIndex+
+) {
System.out.println("Column Name :
"+md.getColumnName(columnIndex));
System.out.println("Column Data Type :
"+md.getColumnTypeName(columnIndex));
System.out.println("Column Size :
"+md.getColumnDisplaySize(columnIndex));
System.out.println("---------------------------------");
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
rs.close();
st.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
EX:
----
package com.durgasoft.app15.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
try {
Class.forName("oracle.jdbc.OracleDriver");
con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system",
"durga");
st = con.createStatement();
rs = st.executeQuery("select * from emp1");
ResultSetMetaData md = rs.getMetaData();
int columnCount = md.getColumnCount();
for(int columnIndex = 1; columnIndex <= columnCount; columnIndex+
+) {
System.out.print(md.getColumnName(columnIndex)+"\t");
}
System.out.println();
System.out.println("--------------------------------------");
while(rs.next()) {
for(int columnIndex = 1; columnIndex <= columnCount;
columnIndex++) {
System.out.print(rs.getString(columnIndex)+"\t");
}
System.out.println();
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
rs.close();
st.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
--> If we execute 'select' sql query with execute() method then JVM will send the
provided select sql query to database Engine, Database Engine will execute that
provided Select sql query , Database Engine will fetch the data from Database and
Database Engine will send that fetched data from Database to Java application in
the form of ResultSet object, but, execute() method will return 'true' as boolean
value.
--> in the above context, if we want to get the generated ResultSet object
reference value explicitly then we have to use the following method from
java.sql.Statement.
EX:
----
package com.durgasoft.app16.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
try {
Class.forName("oracle.jdbc.OracleDriver");
con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system",
"durga");
st = con.createStatement();
boolean b = st.execute("select * from emp1");
System.out.println(b);// true
rs = st.getResultSet();
System.out.println("ENO\tENAME\tESAL\tEADDR");
System.out.println("-----------------------------");
while(rs.next()) {
System.out.print(rs.getInt("ENO")+"\t");
System.out.print(rs.getString("ENAME")+"\t");
System.out.print(rs.getFloat("ESAL")+"\t");
System.out.print(rs.getString("EADDR")+"\n");
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
In Jdbc applications, if we execute non select sql query with execute() method then
JVM will send the provided Non select sql query to Database, where at Database,
Database Engine will execute non select sql query, Database Engine will perform
manipulations on the no of records, it will generate a rowCount value[No of records
which are manipulated with the provided sql query] and Database Engine will send
the generated RowCount value to Java application, but, at Java application
execute() method will return 'false' as boolean value.
EX: boolean b = st.execute("update emp1 set ESAL = ESAL + 500 where ESAL < 10000");
System.out.println(b); // false
In the above context, if we want to get the generated RowCount value explicitly we
have to use the following method from java.sql.Statement.
public int getUpdateCount()throws SQLException
EX:int rowCount = st.getUpdateCount();
EX:
----
package com.durgasoft.app17.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
try {
Class.forName("oracle.jdbc.OracleDriver");
con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system",
"durga");
st = con.createStatement();
boolean b = st.execute("update emp1 set ESAL = ESAL + 500 where
ESAL < 10000");
System.out.println(b);
int rowCount =st.getUpdateCount();
System.out.println("No of Records Updated : "+rowCount);
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
public class Test {
try {
Class.forName("oracle.jdbc.OracleDriver");
con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system",
"durga");
st = con.createStatement();
System.out.println("--------------------------------------");
while(rs.next()) {
for(int columnIndex = 1; columnIndex <= columonCount;
columnIndex++) {
System.out.print(rs.getString(columnIndex)+"\
t");
}
System.out.println();
}
}else {
int rowCount = st.getUpdateCount();
System.out.println("RowCount : "+rowCount);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
br.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Q)In Jdbc applications, to execute Non select sql queries we will use
executeUpdate() method , it will return an integer value as RowCount, in the case
if we execute the DML SQL queries like insert, update and delete through
executeUpdate() then really no of records will be manipulated at database , so we
are able to get the RowCount value from database that RowCount value is returned by
executeUpdate() method, in the case if we execute DDL Sql queries like create,
alter and drop through executeUpdate() method then no records are manipulated at
database, so No RowCount value is generated at Java application , in this context,
which value would be returned by executeUpdate() method as no rowCount Value is
generated from database?
-------------------------------------------------------------------------
Ans:
----
If we execute DDL sql queries like create, alter and drop with executeUpdate()
method then no records are manipulated at Database , No rowCount value is generated
at Java application, in this case, generating a return value from executeUpdate()
is completely depending on the Driver which we used.
If we use Type-1 Driver provided SUN Microsystems then executeUpdate() method will
return -1 value.
If we use Type-4 Driver provided by Oracle or other than Type-1 Drivers then
executeUpdate() method will return 0 value.
EX:
---
package com.durgasoft.app19.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
EX:
----
package com.durgasoft.app20.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
}
}
Q)In Jdbc applications, we will use executeUpdate() method to execute non select
sql queries, but, if we use executeUpdate() method to execute select sql query then
what will be the result in Jdbc applications?
-------------------------------------------------------------------------
Ans:
----
int rowCount = st.executeUpdate("select * from emp1");
In the above situation, if we use Type-1 Driver provided by SUN Microsystems then
JVM will raise an Exception like "java.sql.SQLException: No RowCount was produced".
In the above situation, if we use Type-4 Driver provided by Oracle then JVM will
not raise any Exception, here executeUpdate() method will return an integer value
which is same as the no of records which are existed in the generated ResultSet
object.
In the above cases, we are able to get the generated ResultSet object by using
getResultSet() method.
EX:
----
package com.durgasoft.app21.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:nag", "system",
"durga");
st = con.createStatement();
int rowCount = st.executeUpdate("select * from emp1");
} catch (Exception e) {
e.printStackTrace();
try {
ResultSet rs = st.getResultSet();
System.out.println("ENO\tENAME\tESAL\tEADDR");
System.out.println("-------------------------------");
while(rs.next()) {
System.out.print(rs.getInt("ENO")+"\t");
System.out.print(rs.getString("ENAME")+"\t");
System.out.print(rs.getFloat("ESAL")+"\t");
System.out.print(rs.getString("EADDR")+"\n");
}
} catch (Exception ex) {
ex.printStackTrace();
}
}finally {
try {
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
EX:
----
package com.durgasoft.app22.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
try {
Class.forName("oracle.jdbc.OracleDriver");
con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system",
"durga");
st = con.createStatement();
int rowCount = st.executeUpdate("select * from emp1");
System.out.println("Row Count : "+rowCount);
rs = st.getResultSet();
System.out.println("ENO\tENAME\tESAL\tEADDR");
System.out.println("------------------------------");
while(rs.next()) {
System.out.print(rs.getInt("ENO")+"\t");
System.out.print(rs.getString("ENAME")+"\t");
System.out.print(rs.getFloat("ESAL")+"\t");
System.out.print(rs.getString("EADDR")+"\n");
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
In the above situation, getting an Exception or not is copletly depending the type
of driver which we used.
If we use Type-4 Driver provided by Oracle then JVM will not raise any exception,
here default ResultSet object will be created with default data.
In the above two cases, we are able to get the generated RowCount value explicitly
by using getUpdateCount() method.
EX:
----
package com.durgasoft.app23.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:nag", "system",
"durga");
st = con.createStatement();
ResultSet rs = st.executeQuery("update emp1 set ESAL = ESAL - 500
where ESAL < 10000");
} catch (Exception e) {
e.printStackTrace();
try {
int rowCount = st.getUpdateCount();
System.out.println("No Of Records Updated : "+rowCount);
} catch (Exception ex) {
ex.printStackTrace();
}
}finally {
try {
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
EX:
----
package com.durgasoft.app24.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
2. In the above convention, in finally block, to close the resources we have to use
close() methods, here close() methods are able to raise the exceptions like
SQLException , IOException,... , to handle these exceptions again we have to use
try-catch-finally inside finally block. In this context, providing try-catch-
finally inside finally block is a bit confusion kind of code.
In Jdbc applications, if we use try-with-resources then all the resources which are
declared with 'try' will be closed automatically when flow of execution is coming
outside of the try block , where developers are not required to close the
resources explicitly , if it is the case then it is not required to write finally
block in Jdbc applications.
In JAVA/J2EE , almost all the streams , Connection, Statement, ResultSet ,... are
implementing java.lang.AutoCloseable marker interface.
Syntax:
-------
try(Resource1;
Resource2;
....;
Resource-n;){
----
}catch(Exception e){
----
}
EX:
----
try(
Connection con = DriverManager.getConnection(--,--,--);
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from emp1");
){
-------
}catch(Exception e){
e.printStackTrace();
}
EX:
---
package com.durgasoft.app25.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
Q)Write a Jdbc application to read data from database table and display that data
through an Html file?
-------------------------------------------------------------------------
Ans:
----
package com.durgasoft.app26.test;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
Q)Write a Jdbc application to read data from a particular Database table and
display that data in a text with , seperator?
------------------------------------------------------------------------
ENO,ENAME,ESAL,EADDR
111,AAA,5000,Hyd
222,BBB,6000,Hyd
333,CCC,7000,Hyd
444,DDD,8000,Hyd
EX:
---
package com.durgasoft.app27.test;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
EX:
----
package com.durgasoft.app27.test;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import oracle.jdbc.OracleDriver;
Class c = Class.forName("oracle.jdbc.OracleDriver");
When we execute the above instruction, JVM will perform the following actions.
1) JVM will load the specified Driver class bytecode to the memory.
2) At the time of loading Driver class bytecode to the memory, JVM
will execute static block.
3) Inside static block, JVM will execute
DriverManager.registerDriver() method.
4) After loading Driver class bytecode, JVM will create
java.lang.Class object with the metadata of the Driver class.
EX:
----
package com.durgasoft.app28.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import oracle.jdbc.OracleDriver;
EX:
---
package com.durgasoft.app28.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import oracle.jdbc.OracleDriver;
If we are not performing 'Load and Register Driver' step explicitly then JVM will
load and register the respective driver at the time of establish the connection
between Java application and Database.
EX:
----
package com.durgasoft.app28.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import oracle.jdbc.OracleDriver;
con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system",
"durga");
st = con.createStatement();
rs = st.executeQuery("select * from emp1");
System.out.println("ENO\tENAME\tESAL\tEADDR");
System.out.println("------------------------------");
while(rs.next()) {
System.out.print(rs.getInt("ENO")+"\t");
System.out.print(rs.getString("ENAME")+"\t");
System.out.print(rs.getFloat("ESAL")+"\t");
System.out.print(rs.getString("EADDR")+"\n");
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
EX:
---
package com.durgasoft.app29.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
In the above context, if we want to change the jdbc parameters with out having
changes in Jdbc program we have to use 'properties' file.
If we use 'properties' file approach in Jdbc applications then we have to use the
following steps.
2)In Jdbc Application Create Properties class Object and Load all
the Properties file data through FileInputStream.
FileInputStream fis = new FileInputStream("db.properties");
Properties p = new Properties();
p.load(fis);
EX:
----
package com.durgasoft.app30.test;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;
Class.forName(driverClass);
con = DriverManager.getConnection(url,user,password);
st = con.createStatement();
rs = st.executeQuery("select * from emp1");
System.out.println("ENO\tENAME\tESAL\tEADDR");
System.out.println("------------------------------");
while(rs.next()) {
System.out.print(rs.getInt("ENO")+"\t");
System.out.print(rs.getString("ENAME")+"\t");
System.out.print(rs.getFloat("ESAL")+"\t");
System.out.print(rs.getString("EADDR")+"\n");
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
fis.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
db.properties
--------------
driverClass = oracle.jdbc.OracleDriver
url = jdbc:oracle:thin:@localhost:1521:xe
user = system
password = durga
EX:
----
package com.durgasoft.app30.test;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;
Class.forName("oracle.jdbc.OracleDriver");
con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe",p);
st = con.createStatement();
rs = st.executeQuery("select * from emp1");
System.out.println("ENO\tENAME\tESAL\tEADDR");
System.out.println("------------------------------");
while(rs.next()) {
System.out.print(rs.getInt("ENO")+"\t");
System.out.print(rs.getString("ENAME")+"\t");
System.out.print(rs.getFloat("ESAL")+"\t");
System.out.print(rs.getString("EADDR")+"\n");
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
fis.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Steps:
1. Prepare Factory class with Factory Method:
a)Declare a class .
b)Declare Connection property as static and private.
c)Declare a static block and create Connection object in static block
d)Create a static method and return Connection object for the method
EX:
----
public class ConnectionFactory{
private static Connection con = null;
static{
try{
Class.forName("oracle.jdbc.OracleDriver");
con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","durga")
;
}catch(Exception e){
e.printStackTrace();
}
}
public static Connection getConnection(){
return con;
}
}
2. Get Connection from Factory class and Factory Method in Jdbc applications.
EX:
----
package com.durgasoft.app31.test;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import com.durgasoft.app31.factory.ConnectionFactory;
ConnectionFactory.java
-----------------------
package com.durgasoft.app31.factory;
import java.sql.Connection;
import java.sql.DriverManager;
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection() {
return con;
}
public static void close() {
try {
con.close();
}catch(Exception e) {
e.printStackTrace();
}
}
}
D:\apps>javac Test.java
D:\apps>java Test
1. ADD Student
2. SEARCH Student
3. UPDATE Student
4. DELETE Student
5. EXIT
Your Option : 1
Student Id : S-111
Student Name : Durga
Student Address : Hyd
Status : Student Added Successfully
1. ADD Student
2. SEARCH Student
3. UPDATE Student
4. DELETE Student
5. EXIT
Your Option : 1
Student Id : S-111
Student Name : Durga
Student ADdress : Hyd
Status : Student Existed Already
1. ADD Student
2. SEARCH Student
3. UPDATE Student
4. DELETE Student
5. EXIT
Your Option : 2
Student Id : S-111
Status : Student Existed
Student Details
----------------
Student Id : S-111
Student Name : Durga
Student Address : Hyd
1. ADD Student
2. SEARCH Student
3. UPDATE Student
4. DELETE Student
5. EXIT
Your Option : 2
Student Id : S-222
Status : Student Not Existed
1. ADD Student
2. SEARCH Student
3. UPDATE Student
4. DELETE Student
5. EXIT
Your Option : 3
Student Id : S-111
Student Name [old: Durga] New Value : Nag
Student Address [old : Hyd] New Value : Delhi
Status : Student Updated Successfully
1. ADD Student
2. SEARCH Student
3. UPDATE Student
4. DELETE Student
5. EXIT
Your Option : 3
Student Id : S-333
Status : Student Not Existed
1. ADD Student
2. SEARCH Student
3. UPDATE Student
4. DELETE Student
5. EXIT
Your Option : 4
Student Id : S-111
Status : Student Deleted Successfully
1. ADD Student
2. SEARCH Student
3. UPDATE Student
4. DELETE Student
5. EXIT
Your Option : 4
Student Id : S-444
Status : Student Not Existed
1. ADD Student
2. SEARCH Student
3. UPDATE Student
4. DELETE Student
5. EXIT
Your Option : 5
*******Thank You For Using Student Application*********
We will prepare this application by Following MVC with Enterprise Application Arch
which includes Controller Layer, Service Layer and Dao Layer.
DAO Layer:
----------
--> The main purpose of DAO Layer is to perform Database operations which are
required by Enterprise Application.
--> In Enterprise Application Arch, Service Layer will access Dao layer methods.
Steps:
1. Declare an interface with dao methods declarations.
2. Provide an implementation class for Dao interface and provide
implementation for all the Dao methods.
3. Prepare a Factory class to supply Dao object to Service Layer.
4. Prepare ConnectionFactory to Supply Connection Object to DAO Layer.
Service Layer:
----------------
--> The main intention of Service Layer is to apply some Middleware Services like
Validations, Transactions, Security, Logging.... in Enterprise applications.
--> In Enterprise applications, all the service layer methods are accessed by
Controller Layer.
Steps:
------
1. Prepare an interface with Service methods.
2. Prepare an implementation class to Service interface and provide
implementation for all the service methods.
3. Prepare Factory class to supply Service Object to Controller Layer.
public interface StudentService{
public String addStudent(Student std);
public Student searchStudent(String sid);
public String updateStudent(Student std);
public String deleteStudent(String sid);
}
In this application, to prepare Controller Layer we will use Mian class and main()
method.
setXXX() methods
getXXX() methods
}
--> As per the requirement, if we want to provide input data to the Jdbc
applications through a set of Graphic components like Windows, TextFields,
TextAreas, Checkboxes, Radiobuttons,.....and if we want to provide output data to
the user from jdbc application through the same Collection of Graphic components
then we have to go for 'GUI Applications'
--> To prepare GUI applications, JAVA has provided the following libraries.
1. AWT
2. APPLETS
3. SWING
4. JAVA FX
1. AWT:
-------
--> AWT is 'Abstract Windowing Toolkit', it is an API to prepare GUI
applications.
--> AWT has provided predefined library in a seperate package 'java.awt'.
--> AWT has provided predefined library to rerpesent allmost all the
basic GUI components.
EX:
----
LoginFrame.java
------------------
package com.durgasoft.app33.gui;
import java.awt.Color;
import java.awt.Frame;
Test.java
----------
package com.durgasoft.app33.test;
import com.durgasoft.app33.gui.LoginFrame;
}
}
To display a text message on Frame we have to use the following methgod from
Graphics.
public void drawString(String msg, int x-axis, int y-axis)
EX:
----
LogoFrame.java
---------------
package com.durgasoft.app34.gui;
import java.awt.Color;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Graphics;
Test.java
----------
package com.durgasoft.app34.test;
import com.durgasoft.app34.gui.LogoFrame;
In the above context, which logic we want to execute by clicking on a button that
we have to provide inside listener method.
EX:
---
Windows --> WindowListener --> 7 methods.
-->public void windowClosing(WindwEvent w)
CalculatorFrame.java
---------------------
package com.durgasoft.app35.gui;
import java.awt.Color;
import java.awt.Frame;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
}
@Override
public void windowClosed(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
@Override
public void windowActivated(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
public void windowDeactivated(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
public void windowIconified(WindowEvent e) {
// TODO Auto-generated method stub
}
@Override
public void windowDeiconified(WindowEvent e) {
// TODO Auto-generated method stub
}
}
Test.java
----------
package com.durgasoft.app35.test;
import com.durgasoft.app35.gui.CalculatorFrame;
}
}
IN the above approach, because of windowClosing() method we provided almost all the
methods of WindowListener interface, it is unneccessary to manage these many no of
methods.
To overcome the above problems, AWT has provided an adapter class in the form of
java.awt.event.WindowAdapter.
If we want to provide closing option to the frame with WindowAdapter then we ahve
to extend WindowAdapter class and override only the rehquired method
windowClosing()
EX:
----
WindowListenerImpl.java
------------------------
package com.durgasoft.app35.gui;
import java.awt.Color;
import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
public class CalculatorFrame extends Frame {
public CalculatorFrame() {
this.setVisible(true);
this.setSize(500, 500);
this.setTitle("Calculator Frame");
this.setBackground(Color.green);
WindowListenerImpl listener = new WindowListenerImpl();
this.addWindowListener(listener);
}
Test.java
----------
package com.durgasoft.app35.test;
import com.durgasoft.app35.gui.CalculatorFrame;
}
}
To overcome the above problem, we have to use Anonymous Inner class for
WindowAdapter abstract.
EX:
----
CalculatorFrame.java
---------------------
package com.durgasoft.app35.gui;
import java.awt.Color;
import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
}
}
Test.java
-----------
package com.durgasoft.app35.test;
import com.durgasoft.app35.gui.CalculatorFrame;
--> ActionListener has the following method to execute when we click on Button.
EX:
----
CalculatorFrame.java
---------------------
package com.durgasoft.app36.gui;
import java.awt.Button;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Label;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public CalculatorFrame() {
this.setVisible(true);
this.setSize(500, 500);
this.setTitle("Calculator Frame");
this.setBackground(Color.green);
this.setLayout(new FlowLayout());
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
b1 = new Button("ADD");
b2 = new Button("SUB");
b3 = new Button("MUL");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
this.add(l1); this.add(tf1);
this.add(l2); this.add(tf2);
this.add(l3); this.add(tf3);
this.add(b1); this.add(b2); this.add(b3);
@Override
public void actionPerformed(ActionEvent ae) {
try {
int result = 0;
String label = ae.getActionCommand();
if(label.equalsIgnoreCase("ADD")) {
result = val1 + val2;
}
if(label.equalsIgnoreCase("SUB")) {
result = val1 - val2;
}
if(label.equalsIgnoreCase("MUL")) {
result = val1 * val2;
}
tf3.setText(""+result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Test.java
----------
package com.durgasoft.app36.test;
import com.durgasoft.app36.gui.CalculatorFrame;
GUI-JDBC Application - 1:
-------------------------
LoginFrame.java
---------------
package com.durgasoft.app37.gui;
import java.awt.Button;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Label;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import com.durgasoft.app37.action.UserAction;
public LoginFrame() {
this.setVisible(true);
this.setSize(500, 500);
this.setTitle("Login Frame");
this.setBackground(Color.green);
this.setLayout(new FlowLayout());
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
this.add(l1); this.add(tf1);
this.add(l2); this.add(tf2);
this.add(b);
@Override
public void actionPerformed(ActionEvent e) {
status = userAction.checkLogin(uname,upwd);
repaint();
}
@Override
public void paint(Graphics g) {
Font font = new Font("arial", Font.BOLD, 35);
g.setFont(font);
g.drawString("User Login Status : "+status, 50, 300);
}
UserAction.java
-----------------
package com.durgasoft.app37.action;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public UserAction() {
try {
Class.forName("oracle.jdbc.OracleDriver");
con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system",
"durga");
st = con.createStatement();
} catch (Exception e) {
e.printStackTrace();
}
}
Test.java
----------
package com.durgasoft.app37.test;
import com.durgasoft.app37.gui.LoginFrame;
GUI-JDBC Application-2:
-----------------------
StudentFrame.java
-----------------
package com.durgasoft.app38.gui;
import java.awt.Button;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Label;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import com.durgasoft.app38.action.StudentAction;
public StudentFrame() {
this.setVisible(true);
this.setSize(500, 500);
this.setTitle("Student Frame");
this.setBackground(Color.green);
this.setLayout(new FlowLayout());
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
b = new Button("ADD");
b.addActionListener(this);
this.add(l1); this.add(tf1);
this.add(l2); this.add(tf2);
this.add(l3); this.add(tf3);
this.add(b);
studentAction = new StudentAction();
}
@Override
public void actionPerformed(ActionEvent arg0) {
String sid = tf1.getText();
String sname = tf2.getText();
String saddr = tf3.getText();
status = studentAction.add(sid, sname, saddr);
repaint();
}
@Override
public void paint(Graphics g) {
Font font = new Font("arial", Font.BOLD, 30);
g.setFont(font);
g.drawString("Status : "+status, 50, 300);
}
StudentAction.java
--------------------
package com.durgasoft.app38.action;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
Test.java
----------
package com.durgasoft.app38.test;
import com.durgasoft.app38.gui.StudentFrame;
GUI-JDBC Application-3
------------------------
SQLEditorFrame.java
--------------------
package com.durgasoft.app39.gui;
import java.awt.Button;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Label;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import com.durgasoft.app39.action.SQLEditorAction;
Label l;
TextArea ta;
Button b;
SQLEditorAction sqlEditorAction;
boolean type;
public SQLEditorFrame() {
this.setVisible(true);
this.setSize(700, 700);
this.setTitle("SQL Editor Frame");
this.setBackground(Color.green);
this.setLayout(new FlowLayout());
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
l = new Label("Enter SQL Query");
ta = new TextArea(5, 40);
b = new Button("Execute");
b.addActionListener(this);
this.add(l);
this.add(ta);
this.add(b);
sqlEditorAction = new SQLEditorAction();
}
@Override
public void actionPerformed(ActionEvent ae) {
String query = ta.getText();
type = sqlEditorAction.executeQuery(query);
repaint();
}
@Override
public void paint(Graphics g) {
try {
Font font = new Font("arial",Font.BOLD,30);
g.setFont(font);
if(type == true) {
ResultSet rs = sqlEditorAction.getResultSet();
ResultSetMetaData md = rs.getMetaData();
int columnCount = md.getColumnCount();
int x = 50;
int y = 300;
for(int colIndex = 1; colIndex <= columnCount; colIndex++ )
{
g.drawString(md.getColumnName(colIndex), x, y);
x = x + 150;
}
x = 50;
y = 350;
g.drawString("-------------------------------------------------------------------",
x, y);
x = 50;
y = 400;
while(rs.next()) {
for(int colIndex = 1; colIndex <= columnCount;
colIndex++) {
g.drawString(rs.getString(colIndex), x, y);
x = x + 150;
}
x = 50;
y = y + 50;
}
}else {
int rowCount = sqlEditorAction.getRowCount();
g.drawString("Records Manipulated : "+rowCount, 50, 400);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
SQLEditorAction.java
----------------------
package com.durgasoft.app39.action;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public SQLEditorAction() {
try {
Class.forName("oracle.jdbc.OracleDriver");
con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system",
"durga");
st = con.createStatement();
} catch (Exception e) {
e.printStackTrace();
}
}
Test.java
----------
package com.durgasoft.app39.test;
import com.durgasoft.app39.gui.SQLEditorFrame;
}
}
EX:
---
package com.durgasoft.app40.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
EX:
---
package com.durgasoft.app41.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:mysqldsn", "root",
"root");
st = con.createStatement();
rs = st.executeQuery("select * from emp1");
System.out.println("ENO\tENAME\tESAL\tEADDR");
System.out.println("-----------------------------");
while(rs.next()) {
System.out.print(rs.getInt("ENO")+"\t");
System.out.print(rs.getString("ENAME")+"\t");
System.out.print(rs.getFloat("ESAL")+"\t");
System.out.print(rs.getString("EADDR")+"\n");
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
rs.close();
st.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
EX:
---
package com.durgasoft.app42.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
}
}
Types Of ResultSets:
---------------------
In Jdbc, ResultSets are classified in the following two ways.
1. As per ResultSet Cursor Movement there are two types of ResultSets
1. Forward Only ResultSet
2. Scrollable ResultSet
2. Scrollable ResultSets:
--> It allows to read data in both forward direciton and Backward
direction.
--> There are two types of Scrollable ResultSets.
1. Scroll Sensitive ResultSet.
2. Scroll Insensitive ResultSet
4. Updatable ResultSets:
--> It allows to perform Updations on ResultSet Object.
--> To represent Updatable resultSet object , we will use a
predefined constant from ResultSet interface.
public static final int CONCUR_UPDATABLE
--> In JDBC, the default ResultSet type is "Read Only and Forward
only".
EX:
Statement st = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = st.executeQuery("select * from emp1");
Scrollable ResultSets:
----------------------
--> These ResultSets are able to read data in both Forward
Direction and Backward Direction.
--> To read data in Forward direciton, we have to use the following
methods.
public boolean next()throws SQLException
--> It will check whether next Record is existed or not
from current Cursor position.
--> If next record is existed then it will return true value
--> If next record is not existed then it will return false
value.
--> If we want to read data in Backward direction, first, we have to make sure
whether the ResultSet cursor is existed after the last recoird position.
--> If we want to bring ResultSet cursor to the after last record position we have
to use the following method.
public void afterLast()throws SQLException
--> After bringing ResultSet Cursor to the after last record position we have to
use the following methods to read data in backward direction.
1. public boolean previous()throws SQLException
--> It will check whether previous record is existed or not from
current cursor position.
--> If the previous record is existed then it will return true
value.
--> If the previous record is not existed then it will return
false value.
2. public xxx getXxx(int colIndex/String colName)throws
SQLException
--> It able to return a particular column data.
EX:
---
package com.durgasoft.app42.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/durgadb", "root", "root");
st = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
rs = st.executeQuery("select * from emp1");
Steps:
------
1. Create Scroll Sensitive ResultSet object.
2. Display Data from Scroll Sensitive ResultSet object.
3. Pause the program and goto Database table and perform updations
in Database table.
EX:
---
package com.durgasoft.app43.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/durgadb", "root", "root");
st = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
rs = st.executeQuery("select * from emp1");
System.out.println("Employee Details Before Updations");
System.out.println("ENO\tENAME\tESAL\tEADDR");
System.out.println("--------------------------------");
while(rs.next()) {
System.out.print(rs.getInt("ENO")+"\t");
System.out.print(rs.getString("ENAME")+"\t");
System.out.print(rs.getFloat("ESAL")+"\t");
System.out.print(rs.getString("EADDR")+"\n");
}
System.out.println("Application is in Pausing State, please");
System.out.println("Perform Updations in Database table and
perform Commit operation");
System.in.read();// It will pause the program untill we click on
Enter button
rs.beforeFirst();
System.out.println("Employee Details After Updations");
System.out.println("ENO\tENAME\tESAL\tEADDR");
System.out.println("--------------------------------");
while(rs.next()) {
rs.refreshRow();
System.out.print(rs.getInt("ENO")+"\t");
System.out.print(rs.getString("ENAME")+"\t");
System.out.print(rs.getFloat("ESAL")+"\t");
System.out.print(rs.getString("EADDR")+"\n");
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
rs.close();
st.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Type-4 Driver provided by Oracle is not supporting both Scroll Sensitive ResultSet
object and Scroll Insensitive ResultSets.
Type-1 Driver with Oracle Database is supporting Scrollable ResultSet objects upto
Scroll Sensntive ResultSet, it is not supporting Scroll insensitive ResultSet
object.
Type-1 Driver with MySQL Database is not supporting Scroll Sensitive ResultSet
object and it is supporting Scroll insensntive ResultSet Object.
EX:
---
package com.durgasoft.app43.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
try {
/*
Class.forName("com.mysql.cj.jdbc.Driver");
con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/durgadb", "root", "root");
*/
/*
Class.forName("oracle.jdbc.OracleDriver");
con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system",
"durga");
*/
/*
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:nag", "system",
"durga");
*/
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:mysqldsn", "root",
"root");
st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
rs = st.executeQuery("select * from emp1");
System.out.println("Employee Details Before Updations");
System.out.println("ENO\tENAME\tESAL\tEADDR");
System.out.println("--------------------------------");
while(rs.next()) {
System.out.print(rs.getInt("ENO")+"\t");
System.out.print(rs.getString("ENAME")+"\t");
System.out.print(rs.getFloat("ESAL")+"\t");
System.out.print(rs.getString("EADDR")+"\n");
}
System.out.println("Application is in Pausing State, please");
System.out.println("Perform Updations in Database table and
perform Commit operation");
System.in.read();// It will pause the program untill we click on
Enter button
rs.beforeFirst();
System.out.println("Employee Details After Updations");
System.out.println("ENO\tENAME\tESAL\tEADDR");
System.out.println("--------------------------------");
while(rs.next()) {
rs.refreshRow();
System.out.print(rs.getInt("ENO")+"\t");
System.out.print(rs.getString("ENAME")+"\t");
System.out.print(rs.getFloat("ESAL")+"\t");
System.out.print(rs.getString("EADDR")+"\n");
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
rs.close();
st.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
EX:
---
package com.durgasoft.app44.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
rs.beforeFirst();
rs.next();
System.out.println(rs.getInt("ENO")+","+rs.getString("ENAME")
+","+rs.getFloat("ESAL")+","+rs.getString("EADDR"));
rs.last();
System.out.println(rs.getInt("ENO")+","+rs.getString("ENAME")
+","+rs.getFloat("ESAL")+","+rs.getString("EADDR"));
rs.first();
System.out.println(rs.getInt("ENO")+","+rs.getString("ENAME")
+","+rs.getFloat("ESAL")+","+rs.getString("EADDR"));
rs.absolute(5);
System.out.println(rs.getInt("ENO")+","+rs.getString("ENAME")
+","+rs.getFloat("ESAL")+","+rs.getString("EADDR"));
rs.absolute(-4);
System.out.println(rs.getInt("ENO")+","+rs.getString("ENAME")
+","+rs.getFloat("ESAL")+","+rs.getString("EADDR"));
rs.first();
rs.relative(5);
System.out.println(rs.getInt("ENO")+","+rs.getString("ENAME")
+","+rs.getFloat("ESAL")+","+rs.getString("EADDR"));
rs.last();
rs.relative(-5);
System.out.println(rs.getInt("ENO")+","+rs.getString("ENAME")
+","+rs.getFloat("ESAL")+","+rs.getString("EADDR"));
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
rs.close();
st.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
EX:
---
PlayerFrame.java
-------------------
package com.durgasoft.app45.gui;
import java.awt.Button;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import com.durgasoft.app45.action.PlayerAction;
import com.durgasoft.app45.beans.Employee;
public PlayerFrame() {
this.setVisible(true);
this.setSize(500, 500);
this.setTitle("Player Frame");
this.setLayout(null);
this.setBackground(Color.green);
this.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
System.exit(0);
}
});
b1 = new Button("First");
b2 = new Button("Next");
b3 = new Button("Previous");
b4 = new Button("Last");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
@Override
public void actionPerformed(ActionEvent ae) {
String buttonLabel = ae.getActionCommand();
emp = playerAction.getEmployee(buttonLabel);
repaint();
}
@Override
public void paint(Graphics g) {
Font font = new Font("consolas", Font.BOLD, 35);
g.setFont(font);
if (emp != null) {
g.drawString("ENO : " + emp.getEno(), 100, 150);
g.drawString("ENAME : " + emp.getEname(), 100, 200);
g.drawString("ESAL : " + emp.getEsal(), 100, 250);
g.drawString("EADDR : " + emp.getEaddr(), 100, 300);
}else {
g.drawString("No Employee Found", 100, 250);
}
}
}
PlayerAction.java
-------------------
package com.durgasoft.app45.action;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import com.durgasoft.app45.beans.Employee;
public PlayerAction() {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/durgadb", "root", "root");
st = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
rs = st.executeQuery("select * from emp1");
} catch (Exception e) {
e.printStackTrace();
}
}
public Employee getEmployee(String buttonLabel) {
Employee emp = null;
try {
if (buttonLabel.equalsIgnoreCase("First")) {
flag = rs.first();
}
if (buttonLabel.equalsIgnoreCase("Next")) {
flag = rs.next();
}
if (buttonLabel.equalsIgnoreCase("Previous")) {
flag = rs.previous();
}
if (buttonLabel.equalsIgnoreCase("Last")) {
flag = rs.last();
}
if (flag == true) {
emp = new Employee();
emp.setEno(rs.getInt("ENO"));
emp.setEname(rs.getString("ENAME"));
emp.setEsal(rs.getFloat("ESAL"));
emp.setEaddr(rs.getString("EADDR"));
}else {
emp = null;
}
} catch (Exception e) {
e.printStackTrace();
}
return emp;
}
}
Employee.java
---------------
package com.durgasoft.app45.beans;
Test.java
----------
package com.durgasoft.app45.test;
import com.durgasoft.app45.gui.PlayerFrame;
Updatable ResultSet:
---------------------
--> Updatable ResultSets are the ResultSets, which are able to
allow updations in ResultSet object.
--> In Jdbc applications, by using Updatable ResultSets we are able
to perform the database operations like insert, update and delete with out
using the respective sql queries like 'insert', 'update', 'delete'.
--> In general, in Jdbc applications, when ever we are working
unknown databases , where if we dont know how to write sql queries like insert,
update and delete there we will use 'Updatable ResultSet' object to perform insert,
update and delete operations.
EX:
---
package com.durgasoft.app46.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Scanner;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/durgadb", "root", "root");
st = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
rs = st.executeQuery("select * from emp1");
rs.moveToInsertRow();
rs.insertRow();
System.out.println("Employee "+eno+" Inserted
Successfully");
System.out.print("Onemore Employee[yes/No]? : ");
String option = scanner.next();
if(option.equalsIgnoreCase("yes")) {
continue;
}else {
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
scanner.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
EX:
---
package com.durgasoft.app47.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/durgadb", "root", "root");
st = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
rs = st.executeQuery("select * from emp1");
while(rs.next()) {
float esal = rs.getFloat("ESAL");
if(esal < 10000) {
float newSal = esal + 500;
rs.updateFloat(3, newSal);
rs.updateRow();
System.out.println("Employee "+rs.getInt(1)+" Updated
Successfully");
}
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
rs.close();
st.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Statement st = con.createStatement(
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = st.executeQuery("select * from emp1");
EX:
---
package com.durgasoft.app48.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/durgadb", "root", "root");
st = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
rs = st.executeQuery("select * from emp1");
while(rs.next()) {
int eno = rs.getInt("ENO");
float esal = rs.getFloat("ESAL");
if(esal < 10000) {
rs.deleteRow();
System.out.println("Employee "+eno+" Deleted
Successfully");
}
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
rs.close();
st.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Batch Updations:
-----------------
In general, in Jdbc applications, we will execute multiple sql queries as per the
requirement, in this case, we are able to execute all the sql queries by sending
sql queries one by one from java application to database sequentially, thgis
approach will increase transfermation time , it will increase overall jdbc
application execution time, it will reduce jdbc application performance.
In the above context, executing a group of updation group sql queries is called as
"Batch Updations".
To add an sql query to a batch we have to use the following method from Statement.
To submit batch of sql queries to Database Engine and to make Database Engine to
exewcute batch of sql queries we have to use the following method.
Note: In the batch, if select sql query is included then JVM will raise an
exception like java.sql.BatchUpdateException.
EX:
---
package com.durgasoft.app51.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/durgadb", "root", "root");
st = con.createStatement();
PreparedStatement:
-------------------
In general, in jdbc applications, we will use java.sql.Statement when we want to
execute all sql queries as independent sql queries.
In the above context, every time performing Query Tokenization , Query Parsing and
Query Optimization with out having change is unneccessary, it will increase jdbc
application execution time, it will reduce Jdbc application performance, in this
context, to improve Jdbc application performance then we have to use an alternative
for java.sql.Statement that is java.sql.PreparedStatement.
Therefore, in jdbc applications, when we want to execute the same sql query in the
sequence there to improve jdbc application performance we will use
java.sql.PreparedStatement instead of java.sql.Statement.
EX: pst.setInt(1,111);
pst.setString(2,"AAA");
pst.setFloat(3,5000);
EX:
---
package com.durgasoft.app52.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Scanner;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/durgadb", "root", "root");
pst = con.prepareStatement("insert into emp1 values(?,?,?,?)");
scanner = new Scanner(System.in);
while(true) {
pst.setInt(1, eno);
pst.setString(2, ename);
pst.setFloat(3, esal);
pst.setString(4, eaddr);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
scanner.close();
pst.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
EX:
----
package com.durgasoft.app53.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Scanner;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/durgadb", "root", "root");
pst = con.prepareStatement("update emp1 set ESAL = ESAL + ? where ESAL
< ?");
pst.setInt(1, bonusAmount);
pst.setFloat(2, salRange);
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
scanner.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
EX:
---
package com.durgasoft.app54.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Scanner;
public class Test {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/durgadb", "root", "root");
pst = con.prepareStatement("delete from emp1 where ESAL < ?");
pst.setFloat(1, salRange);
int rowCount = pst.executeUpdate();
System.out.println("Employees Deleted : "+rowCount);
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
scanner.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
EX:
---
package com.durgasoft.app55.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Scanner;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/durgadb", "root", "root");
pst = con.prepareStatement("select * from emp1 where ESAL < ?");
pst.setFloat(1, salRange);
rs = pst.executeQuery();
System.out.println("ENO\tENAME\tESAL\tEADDR");
System.out.println("-----------------------------");
while(rs.next()) {
System.out.print(rs.getInt("ENO")+"\t");
System.out.print(rs.getString("ENAME")+"\t");
System.out.print(rs.getFloat("ESAL")+"\t");
System.out.print(rs.getString("EADDR")+"\n");
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
scanner.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
Steps :
1. Create a table with 'date' type columns.
mysql>create table emp2(ENO int(3) primary key, ENAME char(10), DOJ date, DOB
date);
mysql>commit;
EX:
---
package com.durgasoft.app56.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/durgadb", "root", "root");
pst.setInt(1, 222);
pst.setString(2, "BBB");
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
pst.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
ResultSet rs = pst.executeQuery();
while(rs.next()){
sopln(rs.getInt("ENO")+"\t");
sopln(rs.getString("ENAME")+"\t");
sopln(rs.getDate("DOJ")+"\t");
sopln(rs.getDate("DOB")+"\n");
}
EX:
----
package com.durgasoft.app57.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
Class.forName("com.mysql.cj.jdbc.Driver");
con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/durgadb", "root", "root");
pst = con.prepareStatement("select * from emp2");
rs = pst.executeQuery();
System.out.println("ENO\tENAME\tDOJ\t\tDOB");
System.out.println("---------------------------------------");
while(rs.next()) {
System.out.print(rs.getInt("ENO")+"\t");
System.out.print(rs.getString("ENAME")+"\t");
System.out.print(rs.getDate("DOJ")+"\t");
System.out.print(rs.getDate("DOB")+"\n");
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
rs.close();
pst.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
4. Statement is very much suitable for the DDL SQL queries execution
EX:create, alter, drop,...
PreparedStatement is very much suitable for the DML sql queries execution like
insert, update, delete,...
2. Gather values to the positional parameters and set that values to a batch.
pst.setInt(1,111);
pst.setString(2, "AAA");
pst.setFloat(3,5000);
pst.setString(4, "Hyd");
pst.addBatch();
pst.setInt(1,222);
pst.setString(2, "BBB");
pst.setFloat(3,6000);
pst.setString(4, "Hyd");
pst.addBatch();
pst.setInt(1,333);
pst.setString(2, "CCC");
pst.setFloat(3,7000);
pst.setString(4, "Hyd");
pst.addBatch();
3. Send all the records of data and execute the query at a time :
EX:
---
package com.durgasoft.app58.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/durgadb", "root", "root");
pst = con.prepareStatement("insert into emp1 values(?,?,?,?)");
pst.setInt(1, 111);
pst.setString(2, "AAA");
pst.setFloat(3, 5000);
pst.setString(4, "Hyd");
pst.addBatch();
pst.setInt(1, 222);
pst.setString(2, "BBB");
pst.setFloat(3, 6000);
pst.setString(4, "Pune");
pst.addBatch();
pst.setInt(1, 333);
pst.setString(2, "CCC");
pst.setFloat(3, 7000);
pst.setString(4, "Chennai");
pst.addBatch();
pst.setInt(1, 444);
pst.setString(2, "DDD");
pst.setFloat(3, 8000);
pst.setString(4, "Delhi");
pst.addBatch();
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
pst.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
EX:
---
package com.durgasoft.app59.test;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
try {
Class.forName("oracle.jdbc.OracleDriver");
con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system",
"durga");
st = con.createStatement();
Database:
----------
SQL> select * from reg_Users;
UNAME UPWD
---------- ----------
nagoor durgasoft
durga durga123
Output:
User Name : nagoor'--
Password : software
Valid User, credentials are valid
EX:
---
package com.durgasoft.app60.test;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
try {
Class.forName("oracle.jdbc.OracleDriver");
con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system",
"durga");
pst = con.prepareStatement("select * from reg_Users where UNAME = ? and
UPWD = ?");
pst.setString(1, uname);
pst.setString(2, upwd);
rs = pst.executeQuery();
boolean b = rs.next();
if(b == true) {
System.out.println("Valid User, Credentials are Valid");
}else {
System.out.println("Invalid User, Credentials are Invalid");
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Output:
User Name : durga'--
Password : nagoor
Invalid User, Credentials are Invalid
Database:
SQL> select * from reg_Users;
UNAME UPWD
---------- ----------
nagoor durgasoft
durga durga123
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/durgadb", "root", "root");
st = con.createStatement();
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
EX:
package com.durgasoft.app62.test;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/durgadb", "root", "root");
pst = con.prepareStatement("select * from reg_Users where UNAME = ? and
UPWD = ?");
pst.setString(1, uname);
pst.setString(2, upwd);
rs = pst.executeQuery();
boolean b = rs.next();
if(b == true) {
System.out.println("Valid User, Credentials are valid");
}else {
System.out.println("Invalid User, Credentials are Invalid");
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
If we want to manage blob type data in Jdbc applications then we will use the
following steps.
pst.executeUpdate();
EX:
---
package com.durgasoft.app63.test;
import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
try {
Class.forName("oracle.jdbc.OracleDriver");
con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system",
"durga");
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
fis.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
sopln(rs.getInt("ENO"));
Sopln(rs.getString("ENAME"));
InputStream is = rs.getBinaryStream("EIMAGE");
FileOutputStream fos = new
FileOutputStream("D:/advjava/images/nag_new.jpg");
EX:
---
package com.durgasoft.app64.test;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
Class.forName("oracle.jdbc.OracleDriver");
con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system",
"durga");
pst = con.prepareStatement("select * from emp20 where ENO = ?");
pst.setInt(1, 111);
rs = pst.executeQuery();
rs.next();
System.out.println("Employee Details");
System.out.println("---------------------------");
System.out.println("Employee Number : "+rs.getInt("ENO"));
System.out.println("Employee Name : "+rs.getString("ENAME"));
System.out.println("Employee Image : D:/advjava/images/nag_new.jpg");
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
is.close();
fos.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
CLOB: Character Large Object, CLOB is a data type in databases, it able to manage
large volumes of the character data like documents like xml documents,...
CLOB type operations or conventions are almost all same as BLOB type conventions
only but the following replacements.
EX:
---
package com.durgasoft.app65.test;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
try {
Class.forName("oracle.jdbc.OracleDriver");
con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system",
"durga");
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
fileReader.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
EX:
----
package com.durgasoft.app66.test;
import java.io.FileWriter;
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
try {
Class.forName("oracle.jdbc.OracleDriver");
con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system",
"durga");
pst = con.prepareStatement("select * from webapps where APPNAME = ?");
pst.setString(1, "app01");
rs = pst.executeQuery();
rs.next();
fileWriter = new FileWriter("D:/advjava/documents/depldesc.xml");
reader = rs.getCharacterStream("DEPLDESC");
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
reader.close();
fileWriter.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Syntax:
--------
create or replace procedure procedureName([ParamList])
AS
---Global Declarations----
BEGIN
----
--DB logic---
----
END procName;
/ --> To save and compile procedure
Syntax:
--------
create or replace function functionName([ParamList]) return DataType
AS
---Global Declarations----
BEGIN:
-----
--DB Logic----
-----
return value;
END functionName;
/ --> To save and compile function
In Stored Procedures and Functions, we are able to provide the following three
types of Parameters.
varName IN DataType
2. OUT Type Parameter: It will get data from Procedure / Function Body and it will
send data to procedure / function call.
3. INOUT Type Parameter: It is acting as both IN Type Parameter and OUT Type
Parameter.
varName INOUT DataType
In Jdbc applications, if we want to access stored procedure and function which are
available at database side then we have to use "java.sql.CallableStatement".
EX:
---
/*
create or replace procedure getSal(no IN number, sal OUT float)
AS
BEGIN
select ESAL into sal from emp1 where ENO = no;
END getSal;
/
*/
package com.durgasoft.app67.test;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Types;
try {
Class.forName("oracle.jdbc.OracleDriver");
con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system",
"durga");
cst = con.prepareCall("{call getSal(?,?)}");
cst.setInt(1, 111);
cst.registerOutParameter(2, Types.FLOAT);
cst.execute();
System.out.println("Employee 111 Salary : "+cst.getFloat(2));
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
cst.close();
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
EX:
---
/*
create or replace function getAVGSal(no1 IN number, no2 IN number) return FLOAT
AS
sal1 float;
sal2 float;
BEGIN
select ESAL into sal1 from emp1 where ENO = no1;
select ESAL into sal2 from emp1 where ENO = no2;
return (sal1+sal2)/2;
END getAVGSal;
/
*/
package com.durgasoft.app68.test;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Types;
try {
Class.forName("oracle.jdbc.OracleDriver");
con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system",
"durga");
cst = con.prepareCall("{? = call getAVGSal(?,?)}");
cst.setInt(2, 111);
cst.setInt(3, 222);
cst.registerOutParameter(1, Types.FLOAT);
cst.execute();
System.out.println("111 and 222 Employees AVG Salary :
"+cst.getFloat(1));
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
--> Almost all the databases are supporting a predefined CURSOR type that is
'SYS_REFCURSOR'.
Steps :
1. In Stored Procedures and functions:
a)Declare CURSOR type variable or Parameter.
emp OUT SYS_REFCURSOR;
2. In Jdbc applications:
a)Register OUT Type parameter with CURSOR type.
cst.registerOutParameter(2,OracleTypes.CURSOR);
b)Get results from the OUT Type parameter in the form of ResultSet
object:
EX:
----
/*
create or replace procedure getEmps(salRange IN float, emps OUT SYS_REFCURSOR)
AS
BEGIN
open emps for select * from emp1 where ESAL < salRange;
END getEmps;
/
*/
package com.durgasoft.app69.test;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import oracle.jdbc.internal.OracleTypes;
try {
Class.forName("oracle.jdbc.OracleDriver");
con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system",
"durga");
cst = con.prepareCall("{call getEmps(?,?)}");
cst.setFloat(1, 10000);
cst.registerOutParameter(2, OracleTypes.CURSOR);
cst.execute();
rs = (ResultSet) cst.getObject(2);
System.out.println("ENO\tENAME\tESAL\tEADDR");
System.out.println("----------------------------");
while(rs.next()) {
System.out.print(rs.getInt("ENO")+"\t");
System.out.print(rs.getString("ENAME")+"\t");
System.out.print(rs.getFloat("ESAL")+"\t");
System.out.print(rs.getString("EADDR")+"\n");
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
EX:
----
/*
create or replace function getStudents(addr IN varchar2) return SYS_REFCURSOR
AS
students SYS_REFCURSOR;
BEGIN
open students for select * from student where SADDR = addr;
return students;
END getStudents;
/
*/
package com.durgasoft.app70.test;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import oracle.jdbc.OracleTypes;
try {
Class.forName("oracle.jdbc.OracleDriver");
con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system",
"durga");
cst = con.prepareCall("{? = call getStudents(?)}");
cst.setString(2, "Hyd");
cst.registerOutParameter(1, OracleTypes.CURSOR);
cst.execute();
rs = (ResultSet) cst.getObject(1);
System.out.println("SID\tSNAME\tSADDR");
System.out.println("----------------------");
while(rs.next()) {
System.out.print(rs.getString("SID")+"\t");
System.out.print(rs.getString("SNAME")+"\t");
System.out.print(rs.getString("SADDR")+"\n");
}
} catch (Exception e) {
e.printStackTrace();
}finally {
try {
con.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
EX:
----
package com.durgasoft.app71.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
try {
Class.forName("oracle.jdbc.OracleDriver");
con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","durga")
;
st = con.createStatement();
rs = st.executeQuery("select * from emp1");
System.out.println("ENO\tENAME\tESAL\tEADDR");
System.out.println("-----------------------------");
while(rs.next()){
System.out.print(rs.getInt("ENO")+"\t");
System.out.print(rs.getString("ENAME")+"\t\t");
System.out.print(rs.getFloat("ESAL")+"\t");
System.out.print(rs.getString("EADDR")+"\n");
}
}catch(Exception e){
e.printStackTrace();
}finally{
try {
con.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
}
A --- Automicity
C --- Consistency
I --- Isolation
D --- Durability
Automicity:
------------
In Transactions , we may perform no of operations, here either to perform all the
operations or to perform none of the operations is called as "Automicity" property.
In Transactions, if all the operations are performed then that state is called as
"Success" state, if none of the operations are performed then that state is called
as "Failure" state.
EX: In the transactions like transferring some amount from one account to another
account we have to perform debit operation at sender side and credit operation at
reciever side, so here perform both debit and credit then the transaction state is
"Success" , if no debit and no credit operations are performed then the state of
the transaction is "Failure".
Consistency:
------------
In Transactions, COnsistency Property Says that before the transaction and After
the transaction database state must be stable.
EX: In the transaction like transferring some amount from one account to another
account , the sum of the two accounts balance before the transaction and after the
transaction must be same.
EX: In the transaction like deposit some amount in out account , the sum of the
user amount and balance in out account before the transaction and after the
transaction must be same.
Isolation:
-----------
If we execute more than one transaction on single data item then that transactions
are called as "Concurrent Transactions" and that process is called as "Transactions
Concurrency".
In Transactions, Isolation property says that, one transaction execution must not
give effect to another transaction execution.
If Isolation property is not existed in the transactions then Consistency will not
be achieved and we may get wrong results in the transactions.
EX: If we have joint accounts, there both the persones may perform transactions on
the same account at a time,here there may be a chance to get transactions
concurrency, where we may get wrong results if we are not handling concurrent
transactions.
Durability:
------------
In the transactions, Durability says that, after committing the transactions even
if we have any catastrophic failure then the updations which we performed during
the transactin must be preserved, after getting back the system if we open the
database then the updations which we have done duration the transaction must be
persisted.
If we support for all the ACID properties in any tech then that tech will have
Transactions support in their applications.
JDBC is providing limited support for the transactions, Spring Framework, ORM Tools
like Hibernate are providing very good support for the transactions.
JDBC is providing support for the standalone transactions, not for distributed
transactions.
JDBC has provided predefined library for "Automicity" and "Isolation" properties
only, Consistency and Durability are only test cases that must be performed by the
users / developers explicitly.
In Auto-Commit nature, Connection will send the provided sql query to the Database
Engine and Connection will make Database Engine to execute the sql query and to
store the result of that sql query into the database table permanently.
The above COnnections Auto-Commit nature will not support "Automicity" property of
the transactions, because, it will not allow "rollback" operations over the data
which we stored at present.
con.setAutoCommit(false);
In case of "Non Auto-Commit" operation, Connection will send the provided sql query
to database Engine and Connection will make Database Engine to execute the sql
query and store the results in database table temporarily, it allow rollback
operarations if we need in future.
con.commit(); / con.rollback();
EX:
---
package com.durgasoft.app72.test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
try {
Class.forName("oracle.jdbc.OracleDriver");
con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","durga")
;
con.setAutoCommit(false);
st = con.createStatement();
st.executeUpdate("insert into student values('S1','AAA',79)");
st.executeUpdate("insert into student values('S2','BBB',85)");
st.executeUpdate("insert into student values('S3','CCC',92)");
con.commit();
System.out.println("Transaction Success");
}
catch (Exception e) {
//e.printStackTrace();
try {
con.rollback();
System.out.println("Transaction Failure");
}
catch (SQLException ex) {
ex.printStackTrace();
}
}
finally {
try {
con.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
EX:
---
TX: Transferring some amount from one account to another account , here bothh the
accounts are existed with in the same bank that is with in the same database.
EX:
---
package com.durgasoft.app73;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
try {
Class.forName("oracle.jdbc.OracleDriver");
con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","durga")
;
con.setAutoCommit(false);
st = con.createStatement();
int rowCount1 = st.executeUpdate("update account set BALANCE = BALANCE
- 5000 where ACCNO = 'abc123'");
int rowCount2 = st.executeUpdate("update account set BALANCE = BALANCE
+ 5000 where ACCNO = 'xyz123'");
if(rowCount1 == 1 && rowCount2 == 1){
con.commit();
System.out.println("Transaction Success");
}else{
con.rollback();
System.out.println("Transaction Failure");
}
}
catch (Exception e) {
e.printStackTrace();
try {
con.rollback();
}
catch (SQLException ex) {
ex.printStackTrace();
}
}
finally {
try {
con.close();
}
catch (SQLException e) {
e.printStackTrace();
}
}
}
}
EX: TX: Transferring some ammount from one account to another account , where both
the accounts are existed in two different banks that is in two different databases.
EX:
---
package com.durgasoft.app74;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
try {
Class.forName("oracle.jdbc.OracleDriver");
Class.forName("com.mysql.cj.jdbc.Driver");
oracleCon =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","durga")
;
mysqlCon =
DriverManager.getConnection("jdbc:mysql://localhost:3306/durgadb","root","root");
oracleCon.setAutoCommit(false);
mysqlCon.setAutoCommit(false);
oracleSt = oracleCon.createStatement();
mysqlSt = mysqlCon.createStatement();
}
catch (Exception e) {
//e.printStackTrace();
try {
oracleCon.rollback();
mysqlCon.rollback();
System.out.println("Transaction Failure");
}catch(Exception ex){
ex.printStackTrace();
}
}
finally {
try {
oracleCon.close();
mysqlCon.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}
Sapoint:
---------
If we want to rollback upto a particular part in the transaction which is committed
then we have to use Savepoint.
To block the instructions execuition from the respective savepoint we will use the
following method.
EX:
---
package com.durgasoft.app75;
import java.sql.*;
try {
Class.forName("oracle.jdbc.OracleDriver");
con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","durga")
;
con.setAutoCommit(false);
st = con.createStatement();
st.executeUpdate("insert into emp1 values(111, 'AAA', 5000, 'Hyd')");
Savepoint sp = con.setSavepoint();
st.executeUpdate("insert into emp1 values(222, 'BBB', 6000, 'Hyd')");
con.rollback(sp);
st.executeUpdate("insert into emp1 values(333, 'CCC', 7000, 'Hyd')");
con.commit();
System.out.println("Transaction Success");
}
catch (Exception e) {
e.printStackTrace();
try {
con.rollback();
System.out.println("Transaction Failure");
}
catch (SQLException ex) {
ex.printStackTrace();
}
}
finally {
}
}
Savepoint feature is supported by Type-4 Driver provided by MySQL database upto all
setSavepoint(), rollback(), releaseSavepoint() methods.
EX:
---
package com.durgasoft.app75;
import java.sql.*;
try {
/*
Class.forName("oracle.jdbc.OracleDriver");
con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","durga")
;
*/
Class.forName("com.mysql.cj.jdbc.Driver");
con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/durgadb","root","root");
con.setAutoCommit(false);
st = con.createStatement();
st.executeUpdate("insert into emp1 values(111, 'AAA', 5000, 'Hyd')");
Savepoint sp = con.setSavepoint();
st.executeUpdate("insert into emp1 values(222, 'BBB', 6000, 'Hyd')");
//con.rollback(sp);
con.releaseSavepoint(sp);
st.executeUpdate("insert into emp1 values(333, 'CCC', 7000, 'Hyd')");
con.commit();
System.out.println("Transaction Success");
}
catch (Exception e) {
e.printStackTrace();
try {
con.rollback();
System.out.println("Transaction Failure");
}
catch (SQLException ex) {
ex.printStackTrace();
}
}
finally {
}
}
Isolation Levels:
------------------
If we execute more than one transaction on the same data item then that
transactions are called as Concurrent Transactions and that process is called as
Transactions Concurrency.
The default isolation level for all the connections in Jdbc applications is
"TRANSACTION_READ_COMMITTED" that is 2.
To set a particular isolation level to the connection we will use the following
method.
To get isolation level from the Conneciton we will use the following method.
Here T1 transaction provided updations are lost that's way this problem is called
as "Lost Update" problem.
To come out from this problem we have to use the following method.
con.setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
or
con.setTransactionIsolation(1);
Here the read operation which was performed by T2 transaction over un committed
data is called as Dirty Read.
To come out from this problem we will use the following method.
con.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
con.setTransactionIsolation(2);
con.setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
con.setTransactionIsolation(4);
4. Phantom Read Problem:
-------------------------
1. T1 Perfoems Read operation over the data.
2. T2 transaction deleted the same data.
3. T1 tramsaction read the same data, but, it does not exist.
To come out from this problem we will use the following method.
con.setTransactionIsolation(Connection.TRANSACTION_SERIALIZABLE);
con.setTransactionIsolation(8);
EX:
---
package com.durgasoft.app76;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.List;
static {
try {
Class.forName("oracle.jdbc.OracleDriver");
Connection con1 =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system",
"durga");
Connection con2 =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system",
"durga");
Connection con3 =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system",
"durga");
Connection con4 =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system",
"durga");
Connection con5 =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system",
"durga");
pool.add(con1);
pool.add(con2);
pool.add(con3);
pool.add(con4);
pool.add(con5);
}
catch (Exception e) {
e.printStackTrace();
}
}
EX:
---
package com.durgasoft.app76;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.ArrayList;
import java.util.List;
class MyConnectionPooling{
private static List<Connection> pool = new ArrayList<>(5);
static {
try {
Class.forName("oracle.jdbc.OracleDriver");
Connection con1 =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system",
"durga");
Connection con2 =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system",
"durga");
Connection con3 =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system",
"durga");
Connection con4 =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system",
"durga");
Connection con5 =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "system",
"durga");
pool.add(con1);
pool.add(con2);
pool.add(con3);
pool.add(con4);
pool.add(con5);
}
catch (Exception e) {
e.printStackTrace();
}
}
Note: These methods are varied from DataSource class to dataSource class.
con.close();
EX:
---
package com.durgasoft.app77;
import oracle.jdbc.pool.OracleDataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
}
}
EX:
---
package com.durgasoft.app78;
import com.mysql.cj.jdbc.MysqlDataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
try {
MysqlDataSource ds = new MysqlDataSource();
ds.setURL("jdbc:mysql://localhost:3306/durgadb");
ds.setUser("root");
ds.setPassword("root");
con = ds.getConnection();
st = con.createStatement();
rs = st.executeQuery("select * from emp1");
System.out.println("ENO\tENAME\tESAL\tEADDR");
System.out.println("--------------------------------");
while(rs.next()){
System.out.print(rs.getInt("ENO")+"\t");
System.out.print(rs.getString("ENAME")+"\t\t");
System.out.print(rs.getFloat("ESAL")+"\t");
System.out.print(rs.getString("EADDR")+"\n");
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try{
con.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
}
In general, we will use the following third party vendor provided connection
pooling mechanisms in Jdbc applications.
1. DBCP
2. C3P0
3. Proxool
4. Hikari
-----
-----
-----
1. DBCP:
---------
JARS: commons-pool-version.jar
commons-dbcp-version.jar
commons-logging-version.jar
ojdbc8.jar / mysql-connector-java-8.2.6.jar
DataSource: BasicDataSource
Methods: setDriverClass(---)
setUrl(---)
setUsername(---)
setPassword(---)
getConnection()
setInitialSize(--)
setMaxTotal(---)
----
----
EX:
---
package com.durgasoft.app79;
import org.apache.commons.dbcp2.BasicDataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
BasicDataSource ds = null;
Connection con = null;
Statement st = null;
ResultSet rs = null;
try {
ds = new BasicDataSource();
ds.setDriverClassName("oracle.jdbc.OracleDriver");
ds.setUrl("jdbc:oracle:thin:@localhost:1521:xe");
ds.setUsername("system");
ds.setPassword("durga");
ds.setInitialSize(5);
ds.setMaxTotal(10);
con = ds.getConnection();
st = con.createStatement();
rs = st.executeQuery("select * from emp1");
System.out.println("ENO\tENAME\tESAL\tEADDR");
System.out.println("-------------------------------");
while(rs.next()){
System.out.print(rs.getInt("ENO")+"\t");
System.out.print(rs.getString("ENAME")+"\t\t");
System.out.print(rs.getFloat("ESAL")+"\t");
System.out.print(rs.getString("EADDR")+"\n");
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try{
rs.close();
st.close();
con.close();
ds.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
}
2. C3P0:
---------
JARS: c3p0-version.jar
mchange-commons-java-version.jar
ojdbc8.jar
DataSource: ComboPooledDataSource
Methods : setDriverClass(--)
setJdbcUrl(---)
setUser(---)
setPassword(---)
setMinPoolSize(---)
setMaxPoolSize(---)
----
----
EX:
---
package com.durgasoft.app80;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
ComboPooledDataSource ds = null;
Connection con = null;
Statement st = null;
ResultSet rs = null;
try {
ds = new ComboPooledDataSource();
ds.setDriverClass("oracle.jdbc.OracleDriver");
ds.setJdbcUrl("jdbc:oracle:thin:@localhost:1521:xe");
ds.setUser("system");
ds.setPassword("durga");
ds.setMinPoolSize(5);
ds.setMaxPoolSize(10);
con = ds.getConnection();
st = con.createStatement();
rs = st.executeQuery("select * from emp1");
System.out.println("ENO\tENAME\tESAL\tEADDR");
System.out.println("-------------------------------");
while(rs.next()){
System.out.print(rs.getInt("ENO")+"\t");
System.out.print(rs.getString("ENAME")+"\t\t");
System.out.print(rs.getFloat("ESAL")+"\t");
System.out.print(rs.getString("EADDR")+"\n");
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
rs.close();
st.close();
con.close();
//ds.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
}
3. Proxool
------------
JARS: proxool-version.jar
proxool-cglib-version.jar
commons-logging-version.jar
ojdbc8.jar / mysql-connector-java-version.jar
DataSource : ProxoolDataSource
Methods : setDriver(---)
setDriverUrl(---)
setUser(---)
setPassword(---)
setMinimumConnectionCount(---)
setMaximumConnectionCount(---)
EX:
---
package com.durgasoft.app81;
import org.logicalcobwebs.proxool.ProxoolDataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
ProxoolDataSource ds = null;
Connection con = null;
Statement st = null;
ResultSet rs = null;
try {
ds = new ProxoolDataSource();
ds.setDriver("com.mysql.cj.jdbc.Driver");
ds.setDriverUrl("jdbc:mysql://localhost:3306/durgadb");
ds.setUser("root");
ds.setPassword("root");
ds.setMinimumConnectionCount(5);
ds.setMaximumConnectionCount(15);
con = ds.getConnection();
st = con.createStatement();
rs = st.executeQuery("select * from emp1");
System.out.println("ENO\tENAME\tESAL\tEADDR");
System.out.println("-------------------------------");
while(rs.next()){
System.out.print(rs.getInt("ENO")+"\t");
System.out.print(rs.getString("ENAME")+"\t\t");
System.out.print(rs.getFloat("ESAL")+"\t");
System.out.print(rs.getString("EADDR")+"\n");
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try{
rs.close();
st.close();
con.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
}
4. Hikari:
------------
JARS : HikariCp-version.jar
slf4j-api-version.jar
ojdbc8.jar
DataSource : HikariDataSource
Methods : setDriverClassName(--)
setJdbcUrl(--)
setUsername(--)
setPassword(--)
setMaximumPoolSize(--)
setMinimumIdle(--)
-----
EX:
---
package com.durgasoft.app83;
import com.zaxxer.hikari.HikariDataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
public class Main {
HikariDataSource ds = null;
Connection con = null;
Statement st = null;
ResultSet rs = null;
try {
ds = new HikariDataSource();
ds.setDriverClassName("oracle.jdbc.OracleDriver");
ds.setJdbcUrl("jdbc:oracle:thin:@localhost:1521:xe");
ds.setUsername("system");
ds.setPassword("durga");
ds.setMinimumIdle(5);
ds.setMaximumPoolSize(20);
con = ds.getConnection();
st = con.createStatement();
rs = st.executeQuery("select * from emp1");
System.out.println("ENO\tENAME\tESAL\tEADDR");
System.out.println("-------------------------------");
while(rs.next()){
System.out.print(rs.getInt("ENO")+"\t");
System.out.print(rs.getString("ENAME")+"\t\t");
System.out.print(rs.getFloat("ESAL")+"\t");
System.out.print(rs.getString("EADDR")+"\n");
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try{
rs.close();
st.close();
con.close();
ds.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
}
The main intention of JNDI is to provide Global scope to the resources inorder to
share through out the server that is to all the applications which are deployed in
the application servers.
EX:
---
package com.durgasoft.app84;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Map;
DataSource ds = null;
Connection con = null;
Statement st = null;
ResultSet rs = null;
try {
Hashtable<String, String> ht = new Hashtable<>();
ht.put(Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitialContextFactory");
ht.put(Context.PROVIDER_URL,"t3://localhost:7001");
InitialContext context = new InitialContext(ht);
ds = (DataSource) context.lookup("durgajndi");
con = ds.getConnection();
st = con.createStatement();
rs = st.executeQuery("select * from emp1");
System.out.println("ENO\tENAME\tESAL\tEADDR");
System.out.println("------------------------------");
while(rs.next()){
System.out.print(rs.getInt("ENO")+"\t");
System.out.print(rs.getString("ENAME")+"\t\t");
System.out.print(rs.getFloat("ESAL")+"\t");
System.out.print(rs.getString("EADDR")+"\n");
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try{
rs.close();
st.close();
con.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
}
RowSets:
---------
RowSet is an object, it able to represent the fetched data from database in more
effective than ResultSet object.
Q)To represent fetched data we have already ResultSet then what is the requirement
to go for RowSets?
or
Q)What are the differences between ResultSet and RowSet?
--------------------------------------------------------------------
Ans:
----
1. ResultSet is an interface existed in java.sql package.
RowSet is an interface existed in javax.sql package.
In Jdbc, In RowSets, JoinRowSet is able to merge data from two RowSets into
single RowSet.
2. Disconnected RowSets
EX: CachedRowSet
WebRowSet
JoinRowSet
FilteredRowSet
All the above RowSets are represented in the form of predefined interfaces , but,
all these interfaces are child interfaces to javax.sql.RowSet interface.
javax.sql.RowSet
javax.sql.rowset.JdbcRowSet
javax.sql.rowset.CachedRowSet
javax.sql.rowset.WebRowSet
javax.sql.rowset.JoinRowSet
javax.sql.rowset.FilteredRowSet
For all the above rowset interfaces, all database vendors have provided their own
implementation classes.
SUN Microsystems has provided a reference implementations for all the rowsets in
the form of a package "com.sun.rowset".
com.jdbc.rowset.JdbcRowImpl
com.jdbc.rowset.CachedRowSetImpl
com.jdbc.rowset.WebRowSetImple
com.jdbc.rowset.JoinRowSetImpl
com.jdbc.rowset.FilteredRowSetImpl
For all the RowSet interfaces, Oracle has provided the following predefined
implementation classes in oracle.jdbc.rowset package.
oracle.jdbc.rowset.OracleJdbcRowSet
oracle.jdbc.rowset.OracleCachedRowSet
oracle.jdbc.rowset.OracleWebRowSet
oracle.jdbc.rowset.OracleJoinRowSet
oracle.jdbc.rowset.OracleFilteredRowSet
6. Perform the data base operations like insert record, update record and delete
record ,...
public void updateXXX(int colIndex, xxx value)
public void insertRow()throws SQLException
public void updateRow()throws SQLException
public void deleteRow()throws SQLException
JdbcRowSet:
------------
--> It is Connected RowSet, it required allways connection to perfrom
manipulations with RowSet object.
--> It is almost all same as ResultSet object and it able to perform
the operations as like ResultSet.
EX:
---
package com.durgasoft.app85;
import javax.sql.rowset.JdbcRowSet;
import javax.sql.rowset.RowSetProvider;
try {
rowSet = RowSetProvider.newFactory().createJdbcRowSet();
rowSet.setUrl("jdbc:mysql://localhost:3306/durgadb");
rowSet.setUsername("root");
rowSet.setPassword("root");
rowSet.setCommand("select * from emp1");
rowSet.execute();
System.out.println("Employee Details in Forward Direction");
System.out.println("ENO\tENAME\tESAL\tEADDR");
System.out.println("--------------------------------");
while(rowSet.next()){
System.out.print(rowSet.getInt("ENO")+"\t");
System.out.print(rowSet.getString("ENAME")+"\t\t");
System.out.print(rowSet.getFloat("ESAL")+"\t");
System.out.print(rowSet.getString("EADDR")+"\n");
}
System.out.println();
}
}
To insert records into database table throw RowSet we have to use the following
steps.
1. Create JdbcRowSet:
JdbcRowSet rowSet = RowSetProvider.newFactory().createJdbcRowSet();
5. Move Cursor to after the last record position and take buffer:
rowSet.afterLast();
or
rowSet.moveToInsertRow();
EX:
---
package com.durgasoft.app86;
import javax.sql.rowset.JdbcRowSet;
import javax.sql.rowset.RowSetProvider;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
while(true){
System.out.print("Employee Number : ");
int eno = Integer.parseInt(br.readLine());
System.out.print("Employee Name : ");
String ename = br.readLine();
System.out.print("Employee Salary : ");
float esal = Float.parseFloat(br.readLine());
System.out.print("Employee Address : ");
String eaddr = br.readLine();
rowSet.updateInt(1,eno);
rowSet.updateString(2,ename);
rowSet.updateFloat(3,esal);
rowSet.updateString(4,eaddr);
rowSet.insertRow();
System.out.println("Employee "+eno+" Inserted Successfully");
System.out.print("One more Employee[Yes/No]? : ");
String option = br.readLine();
if(option.equalsIgnoreCase("yes")){
continue;
}else{
break;
}
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try{
br.close();
rowSet.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
}
EX:
---
package com.durgasoft.app87;
import javax.sql.rowset.JdbcRowSet;
import javax.sql.rowset.RowSetProvider;
try {
rowSet = RowSetProvider.newFactory().createJdbcRowSet();
rowSet.setUrl("jdbc:mysql://localhost:3306/durgadb");
rowSet.setUsername("root");
rowSet.setPassword("root");
rowSet.setCommand("select * from emp1");
rowSet.execute();
while(rowSet.next()){
float sal = rowSet.getFloat("ESAL");
if(sal < 10000){
float newSal = sal + 500;
rowSet.updateFloat(3,newSal);
rowSet.updateRow();
System.out.println("Employee "+rowSet.getInt("ENO")+" Updated
Successfully");
}
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try{
rowSet.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
}
EX:
---
package com.durgasoft.app88;
import javax.sql.rowset.JdbcRowSet;
import javax.sql.rowset.RowSetProvider;
while(rowSet.next()){
float sal = rowSet.getFloat("ESAL");
if(sal < 10000){
int eno = rowSet.getInt("ENO");
rowSet.deleteRow();
System.out.println("Employee "+eno+" Deleted Successfully");
}
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try{
rowSet.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
}
CachedRowSet:
--------------
--> CachedRowSet is diconnected RowSet, it does not required connection allways, it
will establish connection when we perform database operations, when database
operations are completed automatocally connection will be diconnected.
--> The main intention of CachedRowSet is to manage the results in cache memory for
the future reusability. In enterprise applications, we may get the same results no
of times , in enterprise applications every time we will interact with the database
and we will get the same results every time, this approach will consume more no of
system resources and it will take more execution time, it will reduce application
performance,
rowSet.setUrl("---");
rowSet.setUsername("--");
rowSet.setpassword("---");
4. Read data from CachedRow in both Forward direction and Backward direction:
import javax.sql.rowset.CachedRowSet;
import javax.sql.rowset.RowSetProvider;
try {
rowSet = RowSetProvider.newFactory().createCachedRowSet();
rowSet.setUrl("jdbc:mysql://localhost:3306/durgadb");
rowSet.setUsername("root");
rowSet.setPassword("root");
}
}
con.setAutoCommit(false);
rowSet.moveToInsertRow();
rowSet.updateInt(1,111);
rowSet.updateString(2,"AAA");
rowSet.updateFloat(3,5000);
rowSet.updateString(4, "Hyd");
rowSet.insertRow();
rowSet.moveToCurrentRow();
rowSet.acceptChanges();
EX:
----
package com.durgasoft.app90;
import javax.sql.rowset.CachedRowSet;
import javax.sql.rowset.RowSetProvider;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Scanner;
while(true){
System.out.print("Employee Number : ");
int eno = scanner.nextInt();
System.out.print("Employee Name : ");
String ename = scanner.next();
System.out.print("Employee Salary : ");
float esal = scanner.nextFloat();
System.out.print("Employee Address : ");
String eaddr = scanner.next();
rowSet.moveToInsertRow();
rowSet.updateInt(1,eno);
rowSet.updateString(2,ename);
rowSet.updateFloat(3,esal);
rowSet.updateString(4, eaddr);
rowSet.insertRow();
rowSet.moveToCurrentRow();
rowSet.acceptChanges();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try{
rowSet.close();
scanner.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
}
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con =
Drivermanager.getConnection("jdbc:mysql://localhost:3306/durgadb","root","root");
con.setAutoCommit(false);
rowSet.absolute(3);
rowSet.updateRow();
rowSet.moveToCurrentRow();
rowSet.acceptChanges();
EX:
---
package com.durgasoft.app91;
import javax.sql.rowset.CachedRowSet;
import javax.sql.rowset.RowSetProvider;
import java.sql.Connection;
import java.sql.DriverManager;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/durgadb","root","root");
con.setAutoCommit(false);
rowSet = RowSetProvider.newFactory().createCachedRowSet();
rowSet.setCommand("select * from emp1");
rowSet.execute(con);
while(rowSet.next()){
float sal = rowSet.getFloat("ESAL");
if(sal < 10000){
float newSal = sal + 500;
rowSet.updateFloat(3, newSal);
rowSet.updateRow();
rowSet.moveToCurrentRow();
rowSet.acceptChanges();
System.out.println("Employee "+rowSet.getInt("ENO")+" Updated
Successfully");
}
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try{
con.close();
rowSet.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
}
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con =
Drivermanager.getConnection("jdbc:mysql://localhost:3306/durgadb","root","root");
con.setAutoCommit(false);
rowSet.absolute(4);
6. Delete Record:
rowSet.deleteRow();
rowSet.moveToCurrentRow();
rowSet.acceptChanges();
EX:
---
package com.durgasoft.app92;
import javax.sql.rowset.CachedRowSet;
import javax.sql.rowset.RowSetProvider;
import java.sql.Connection;
import java.sql.DriverManager;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/durgadb","root","root");
con.setAutoCommit(false);
rowSet = RowSetProvider.newFactory().createCachedRowSet();
rowSet.setCommand("select * from emp1");
rowSet.execute(con);
while(rowSet.next()){
float sal = rowSet.getFloat("ESAL");
if(sal < 10000){
int eno = rowSet.getInt("ENO");
rowSet.deleteRow();
//rowSet.moveToCurrentRow();
rowSet.acceptChanges();
System.out.println("Employee "+eno+" Deleted Successfully");
}
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try{
con.close();
rowSet.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
}
WebRowSet:
-----------
--> The main intention of WebRowSet is
1. To get data from database table and to manage that data in the
form of an XML file
2. To perform the operations like insert, update and delete from
an XML file to Database table
--> If the fetched data is available in the form of XML file then it
is possible to carry data from Java application to some other technology
applications like .Net, Python,...
rowSet.setUrl("jdbc:mysql://localhost:3306/durgadb");
rowSet.setUsername("root");
rowSet.setPassword("root");
rowSet.execute();
rowSet.writeXml(fos);
EX:
---
package com.durgasoft.app93;
import javax.sql.rowset.RowSetProvider;
import javax.sql.rowset.WebRowSet;
import java.io.FileOutputStream;
try {
rowSet = RowSetProvider.newFactory().createWebRowSet();
rowSet.setUrl("jdbc:mysql://localhost:3306/durgadb");
rowSet.setUsername("root");
rowSet.setPassword("root");
}
}
If we execute the above program then we will get emp.xml file which includes the
following three types of tags mainly.
1.<properties> tag
2.<metadata> tag
3.<data> tag
Where <properties> tag is able to manage all the properties of the RowSet object
like command, url, username, password, table name,....
Where <metadata> tag is able to manage metadata of the RowSet which includes no of
columns, column names, database name, column data types,....
Where <data> tag contains the actual records data in the form of <currentRow> tags.
EX: emp.xml
------------
<?xml version="1.0"?>
<webRowSet xmlns="http://java.sun.com/xml/ns/jdbc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/jdbc
http://java.sun.com/xml/ns/jdbc/webrowset.xsd">
<properties>
<command>select * from emp1</command>
<concurrency>1008</concurrency>
<datasource><null/></datasource>
<escape-processing>true</escape-processing>
<fetch-direction>1000</fetch-direction>
<fetch-size>0</fetch-size>
<isolation-level>2</isolation-level>
<key-columns>
</key-columns>
<map>
</map>
<max-field-size>0</max-field-size>
<max-rows>0</max-rows>
<query-timeout>0</query-timeout>
<read-only>true</read-only>
<rowset-type>ResultSet.TYPE_SCROLL_INSENSITIVE</rowset-type>
<show-deleted>false</show-deleted>
<table-name>emp1</table-name>
<url>jdbc:mysql://localhost:3306/durgadb</url>
<sync-provider>
<sync-provider-name>com.sun.rowset.providers.RIOptimisticProvider</sync-
provider-name>
<sync-provider-vendor>Oracle Corporation</sync-provider-vendor>
<sync-provider-version>1.0</sync-provider-version>
<sync-provider-grade>2</sync-provider-grade>
<data-source-lock>1</data-source-lock>
</sync-provider>
</properties>
<metadata>
<column-count>4</column-count>
<column-definition>
<column-index>1</column-index>
<auto-increment>false</auto-increment>
<case-sensitive>false</case-sensitive>
<currency>false</currency>
<nullable>0</nullable>
<signed>true</signed>
<searchable>true</searchable>
<column-display-size>10</column-display-size>
<column-label>ENO</column-label>
<column-name>ENO</column-name>
<schema-name></schema-name>
<column-precision>10</column-precision>
<column-scale>0</column-scale>
<table-name>emp1</table-name>
<catalog-name>durgadb</catalog-name>
<column-type>4</column-type>
<column-type-name>INT</column-type-name>
</column-definition>
<column-definition>
<column-index>2</column-index>
<auto-increment>false</auto-increment>
<case-sensitive>false</case-sensitive>
<currency>false</currency>
<nullable>1</nullable>
<signed>false</signed>
<searchable>true</searchable>
<column-display-size>10</column-display-size>
<column-label>ENAME</column-label>
<column-name>ENAME</column-name>
<schema-name></schema-name>
<column-precision>10</column-precision>
<column-scale>0</column-scale>
<table-name>emp1</table-name>
<catalog-name>durgadb</catalog-name>
<column-type>1</column-type>
<column-type-name>CHAR</column-type-name>
</column-definition>
<column-definition>
<column-index>3</column-index>
<auto-increment>false</auto-increment>
<case-sensitive>false</case-sensitive>
<currency>false</currency>
<nullable>1</nullable>
<signed>true</signed>
<searchable>true</searchable>
<column-display-size>12</column-display-size>
<column-label>ESAL</column-label>
<column-name>ESAL</column-name>
<schema-name></schema-name>
<column-precision>12</column-precision>
<column-scale>0</column-scale>
<table-name>emp1</table-name>
<catalog-name>durgadb</catalog-name>
<column-type>7</column-type>
<column-type-name>FLOAT</column-type-name>
</column-definition>
<column-definition>
<column-index>4</column-index>
<auto-increment>false</auto-increment>
<case-sensitive>false</case-sensitive>
<currency>false</currency>
<nullable>1</nullable>
<signed>false</signed>
<searchable>true</searchable>
<column-display-size>10</column-display-size>
<column-label>EADDR</column-label>
<column-name>EADDR</column-name>
<schema-name></schema-name>
<column-precision>10</column-precision>
<column-scale>0</column-scale>
<table-name>emp1</table-name>
<catalog-name>durgadb</catalog-name>
<column-type>1</column-type>
<column-type-name>CHAR</column-type-name>
</column-definition>
</metadata>
<data>
<currentRow>
<columnValue>111</columnValue>
<columnValue>AAA</columnValue>
<columnValue>5000.0</columnValue>
<columnValue>Hyd</columnValue>
</currentRow>
<currentRow>
<columnValue>222</columnValue>
<columnValue>BBB</columnValue>
<columnValue>6000.0</columnValue>
<columnValue>Hyd</columnValue>
</currentRow>
<currentRow>
<columnValue>333</columnValue>
<columnValue>CCC</columnValue>
<columnValue>7000.0</columnValue>
<columnValue>Hyd</columnValue>
</currentRow>
<currentRow>
<columnValue>444</columnValue>
<columnValue>DDD</columnValue>
<columnValue>8000.0</columnValue>
<columnValue>Hyd</columnValue>
</currentRow>
<currentRow>
<columnValue>555</columnValue>
<columnValue>EEE</columnValue>
<columnValue>9000.0</columnValue>
<columnValue>Hyd</columnValue>
</currentRow>
</data>
</webRowSet>
<insertRow>
<columnValue>111</columnValue>
<columnValue>AAA</columnValue>
<columnValue>5000</columnValue>
<columnValue>Hyd</columnValue>
</insertRow>
<currentRow>
<columnValue>555</columnValue>
<columnValue>EEE</columnValue>
<updateRow>XXX</updateRow>
<columnValue>8000</columnValue>
<updateRow>9000</updateRow>
<columnValue>Hyd</columnValue>
<updateRow>Chennai</updateRow>
</currentRow>
<deleteRow>
<columnValue>111</columnValue>
<columnValue>AAA</columnValue>
<columnValue>5000</columnValue>
<columnValue>Hyd</columnValue>
</deleteRow>
Class.forName("com.mysql.cj.jdbc.Driver")
3. Establish Connection:
con.setAutoCommit(false);
rowSet.execute(con);
9. Read data from FileReader and store that data in RowSet object:
rowSet.readXml(fr);
10. Move cursor to the current row and accept the changes:
rowSet.moveToCurrentRow();
rowSet.acceptChanges();
EX:
---
emp.xml:
---------
<?xml version="1.0"?>
<webRowSet xmlns="http://java.sun.com/xml/ns/jdbc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/jdbc
http://java.sun.com/xml/ns/jdbc/webrowset.xsd">
<properties>
<command>select * from emp1</command>
<concurrency>1008</concurrency>
<datasource><null/></datasource>
<escape-processing>true</escape-processing>
<fetch-direction>1000</fetch-direction>
<fetch-size>0</fetch-size>
<isolation-level>2</isolation-level>
<key-columns>
</key-columns>
<map>
</map>
<max-field-size>0</max-field-size>
<max-rows>0</max-rows>
<query-timeout>0</query-timeout>
<read-only>true</read-only>
<rowset-type>ResultSet.TYPE_SCROLL_INSENSITIVE</rowset-type>
<show-deleted>false</show-deleted>
<table-name>emp1</table-name>
<url>jdbc:mysql://localhost:3306/durgadb</url>
<sync-provider>
<sync-provider-name>com.sun.rowset.providers.RIOptimisticProvider</sync-
provider-name>
<sync-provider-vendor>Oracle Corporation</sync-provider-vendor>
<sync-provider-version>1.0</sync-provider-version>
<sync-provider-grade>2</sync-provider-grade>
<data-source-lock>1</data-source-lock>
</sync-provider>
</properties>
<metadata>
<column-count>4</column-count>
<column-definition>
<column-index>1</column-index>
<auto-increment>false</auto-increment>
<case-sensitive>false</case-sensitive>
<currency>false</currency>
<nullable>0</nullable>
<signed>true</signed>
<searchable>true</searchable>
<column-display-size>10</column-display-size>
<column-label>ENO</column-label>
<column-name>ENO</column-name>
<schema-name></schema-name>
<column-precision>10</column-precision>
<column-scale>0</column-scale>
<table-name>emp1</table-name>
<catalog-name>durgadb</catalog-name>
<column-type>4</column-type>
<column-type-name>INT</column-type-name>
</column-definition>
<column-definition>
<column-index>2</column-index>
<auto-increment>false</auto-increment>
<case-sensitive>false</case-sensitive>
<currency>false</currency>
<nullable>1</nullable>
<signed>false</signed>
<searchable>true</searchable>
<column-display-size>10</column-display-size>
<column-label>ENAME</column-label>
<column-name>ENAME</column-name>
<schema-name></schema-name>
<column-precision>10</column-precision>
<column-scale>0</column-scale>
<table-name>emp1</table-name>
<catalog-name>durgadb</catalog-name>
<column-type>1</column-type>
<column-type-name>CHAR</column-type-name>
</column-definition>
<column-definition>
<column-index>3</column-index>
<auto-increment>false</auto-increment>
<case-sensitive>false</case-sensitive>
<currency>false</currency>
<nullable>1</nullable>
<signed>true</signed>
<searchable>true</searchable>
<column-display-size>12</column-display-size>
<column-label>ESAL</column-label>
<column-name>ESAL</column-name>
<schema-name></schema-name>
<column-precision>12</column-precision>
<column-scale>0</column-scale>
<table-name>emp1</table-name>
<catalog-name>durgadb</catalog-name>
<column-type>7</column-type>
<column-type-name>FLOAT</column-type-name>
</column-definition>
<column-definition>
<column-index>4</column-index>
<auto-increment>false</auto-increment>
<case-sensitive>false</case-sensitive>
<currency>false</currency>
<nullable>1</nullable>
<signed>false</signed>
<searchable>true</searchable>
<column-display-size>10</column-display-size>
<column-label>EADDR</column-label>
<column-name>EADDR</column-name>
<schema-name></schema-name>
<column-precision>10</column-precision>
<column-scale>0</column-scale>
<table-name>emp1</table-name>
<catalog-name>durgadb</catalog-name>
<column-type>1</column-type>
<column-type-name>CHAR</column-type-name>
</column-definition>
</metadata>
<data>
<currentRow>
<columnValue>111</columnValue>
<columnValue>AAA</columnValue>
<columnValue>5000.0</columnValue>
<updateRow>5500</updateRow>
<columnValue>Hyd</columnValue>
</currentRow>
<currentRow>
<columnValue>222</columnValue>
<columnValue>BBB</columnValue>
<columnValue>6000.0</columnValue>
<updateRow>6500</updateRow>
<columnValue>Hyd</columnValue>
</currentRow>
<currentRow>
<columnValue>333</columnValue>
<columnValue>CCC</columnValue>
<columnValue>7000.0</columnValue>
<updateRow>7500</updateRow>
<columnValue>Hyd</columnValue>
</currentRow>
<currentRow>
<columnValue>444</columnValue>
<columnValue>DDD</columnValue>
<columnValue>8000.0</columnValue>
<updateRow>8500</updateRow>
<columnValue>Hyd</columnValue>
</currentRow>
<deleteRow>
<columnValue>555</columnValue>
<columnValue>EEE</columnValue>
<columnValue>9000.0</columnValue>
<updateRow>9500</updateRow>
<columnValue>Hyd</columnValue>
</deleteRow>
<insertRow>
<columnValue>666</columnValue>
<columnValue>FFF</columnValue>
<columnValue>5000</columnValue>
<updateRow>5500</updateRow>
<columnValue>Hyd</columnValue>
</insertRow>
</data>
</webRowSet>
package com.durgasoft.app94;
import javax.sql.rowset.RowSetProvider;
import javax.sql.rowset.WebRowSet;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/durgadb","root","root");
con.setAutoCommit(false);
rowSet = RowSetProvider.newFactory().createWebRowSet();
rowSet.setCommand("select * from emp1");
rowSet.execute(con);
rowSet.moveToCurrentRow();
rowSet.acceptChanges();
System.out.println("insert, update and delete operations are Success");
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try{
fileReader.close();
con.close();
rowSet.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
}
JoinRowSet:
------------
--> The main intention of JoinRowSet is to join two RowSet objects content into
single RowSet object:
Steps:
-------
1. Create two tables with a Join Column:
mysql>create table student(SID char(5) primary key, SNAME char(10), SADDR char(10),
CID char(5));
2. create table course(CID char(5) primary key, CNAME char(10), CCOST int(5));
rowSet.addRowSet(rowSet1,4);
rowSet.addRowSet(rowSet2,1);
while(rowSet.next()){
-----
EX:
----
package com.durgasoft.app95;
import javax.sql.rowset.CachedRowSet;
import javax.sql.rowset.JoinRowSet;
import javax.sql.rowset.RowSetProvider;
import java.sql.Connection;
import java.sql.DriverManager;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/durgadb","root","root");
rowSet1 = RowSetProvider.newFactory().createCachedRowSet();
rowSet1.setCommand("select * from student");
rowSet1.execute(con);
rowSet2 = RowSetProvider.newFactory().createCachedRowSet();
rowSet2.setCommand("select * from course");
rowSet2.execute(con);
joinRowSet = RowSetProvider.newFactory().createJoinRowSet();
joinRowSet.addRowSet(rowSet1,"CID");
joinRowSet.addRowSet(rowSet2,"CID");
System.out.println("SID\t\tSNAME\tSADDR\tCID\t\tCNAME\tCCOST");
System.out.println("------------------------------------------------");
while(joinRowSet.next()){
System.out.print(joinRowSet.getString("SID")+"\t");
System.out.print(joinRowSet.getString("SNAME")+"\t\t");
System.out.print(joinRowSet.getString("SADDR")+"\t\t");
System.out.print(joinRowSet.getString("CID")+"\t");
System.out.print(joinRowSet.getString("CNAME")+"\t");
System.out.print(joinRowSet.getInt("CCOST")+"\n");
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try{
con.close();
rowSet1.close();
rowSet2.close();
joinRowSet.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
}