Natraj JDBC
Natraj JDBC
(ii)
(iii)
Persistence store
(2)
Persistence data
(3)
Persistence logic
(4)
Persistence Technology
CRUD/CURD/SCUD
o C-Create(insert)
o R- Read (select)
o U-Update(modify)
o D- Delete
Files
(b)
(c)
Xopen
(b)
(c)
Continue
2015-03-12
Proprietary technology:The vendor that has given these technologies are only
allowed to develop software based on the technologies.
Eg:-All Microsoft Technology.
java.sql.Driver (interface)
^
|
extends
sun.jdbc.odbc.jdbcOdbcDriverInterfacd (Interface)
^
| implements
sum.jdbc.odbc
Even though multiple class in every jdbc driver we just know
diver class name in order to activate and use these jdbc driver in
our java application.
Every Jdbc driver is identified with its driver class. It is the class
supplied by vendor company of jdbc driver implementing
java.sql.Driver Interface directly or indirectly.
Upto jdk1.7 we get one built in jdbc driver given by sum
Microsoft in rt.jar file. This jdbc driver is identified with its driver
class .
sum.jdbc.odbc.JdbcOdbcDriver
(package
)|(class name)
(2)
(3)
(2)
(3)
(4)
(5)
Partial Architecture of Type-1 jdbc driver:This type-1 driver is designed to talk with Data base software
directly. It is designed talk the support of odbc driver to interact
with database software.
We can use one type-1 jdbc driver to talk with multiple database
software by take support of multiple odbc driver.
The jdk supplied build-in jdbc driver is given based on type-1
architecture. Its driver class name is
sum.jdbc.odbc.JdbcOdbcDriver.
So for only sun Microsoft is giving type-1 diver along with jdk
software installation .(up to jdk 1.7)
Every java application contain one built in service called
Drivermanager service.
Having the capability to manage set of jdbc dirvers.
TO access these services in our application we can use
java.sql.DriverManager class.
(2)
(2)
Type-1 jdk dirver uses odbc driver for oracle based on the dsn
that is specified (oradsn).
(3)
Q:Connection
con=DriverManager.getConnction(jdbc:odbc:oradsn,scott,tiger)
When java.sql.Connection is an interface how can we say
DriverManager.getConnection(-, -, -) is returning jdbc
connection object.
Ans:
02-28-2015
}
Different ways of reading input from keyboard.
1) Using Scanner Class (jdk 1.5 onbord)
2) Using Command line arguments
3) Using user defined system property
4) Using BufferedReader
5) Using java.io.Console (jdk 1.6)
import java.io.*;
import java.util.*;
public class ReadInput
{
public static void main(String args[]) throws IOException
{
Scanner sc =new Scanner(System.in);
System.out.println("Enter Name-1 : ");
String name1=sc.next();
String name2=args[0];
String name3=System.getProperty("myName");
//using stream
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter name-4 :");
String name4=br.readLine();
//Using console
System.out.println("Enter Name-5 : ");
Console cons=System.console();
String name5=cons.readLine();//display value
System.out.println(name1+" "+name2+" "+name3+" "+name4+"
"+name5);
}>javac ReadInput.java
}> java DmyName=Raja3 ReadInput Raja2
Setting command line argument
Setting System property value
Once specified passing command line argument is mandatory
Once specified passing system property is optional.
Q: - can you explain different way of registering jdbc DriverManager
with DriverManager service
Approach-1: sun.jdbc.odbc.JdbcOdbcDriver obj=new
sun.jdbc.odbc.JdbcOdbcDriver(obj);
import java.sql.*;
public class ConnTest
{
public static void main(String args[]) throws Exception
{ //Register odbcDriver(type 1)
{
System.out.println("Connection not established");
}
else
System.out.println("connection is established");
}//main method closed
}//class closed
Approach-3
sun.jdbc.odbc.JdbcOdbcDriver obj=new
sun.jdbc.odbc.JdbcOdbcDriver();
import java.sql.*;
public class ConnTest3
{
public static void main(String args[]) throws Exception
{
sun.jdbc.odbc.JdbcOdbcDriver obj=new
sun.jdbc.odbc.JdbcOdbcDriver();
database software
Connection
con=DriverManager.getConnection("jdbc:odbc:oradsn","scott","tiger");
if(con==null)
{
System.out.println("Connection not established");
}
else
System.out.println("connection is established");
} }
Approach-4
new sun.jdbc.odbc.JdbcOdbcDriver();
Approach-4 is similar to approach-3 so it is not recommended to
use
Note: In approach- 3&4 the driver will registered only for one time but
explicitly created object of driver class will be wasted.
new sun.jdbc.odbc.JdbcOdbcDriver(); // register diver
Connection
con=DriverManager.getConnection("jdbc:odbc:oradsn","scott","tiger");
import java.sql.*;
public class ConnTest4
{
public static void main(String args[]) throws Exception
{
new sun.jdbc.odbc.JdbcOdbcDriver(); // register diver
Connection
con=DriverManager.getConnection("jdbc:odbc:oradsn","scott","tiger");
if(con==null)
{
System.out.println("Connection not established");
}
else
System.out.println("connection is established");
}//main method closed
}//class closed
Approach-5
public class ConnTest5 extends sun.jdbc.odbc.JdbcOdbcDriver
{
public static void main(String args[]) throws Exception
{
Connection
con=DriverManager.getConnection("jdbc:odbc:oradsn","scott","tiger");
In the above code when jvm load contest class it also loads its
super class called Driver class in this process static block driver
class execute and driver will be registered.
The above code is not recommended because it does not let our
application class to extends from other class like from applet,
HTTPservlet
import java.sql.*;
public class ConnTest5 extends sun.jdbc.odbc.JdbcOdbcDriver
{
public static void main(String args[]) throws Exception
{
Connection
con=DriverManager.getConnection("jdbc:odbc:oradsn","scott","tiger");
if(con==null)
{
System.out.println("Connection not established");
}
else
System.out.println("connection is established");
}//main method closed
}//class closed
Approach-6
class.forName(sun.jdbc.odbc.JdbcOdbeDriver)
This is a recommended approach because it registered the driver
only for one time and does not create any west object for driver
class
import java.sql.*;
public class ConnTest6
{
public static void main(String args[]) throws Exception
{
if(Class.forName("sun.jdbc.odbc.JdbcOdbcDriver")==null)
{
System.out.println("Connection not established");
}
else
System.out.println("connection is established");
}//main method closed
}//class closed
Approach=7
Connection
con=DriverManager.getConnection("jdbc:odbc:oradsn","scott","tiger");
if(con==null)
{
System.out.println("Connection not established");
}
else
System.out.println("connection is established");
}//main method closed
}//class closed
>javac ConnTest8.java
>java Dmydriver=sun.jdbc.odbc.JdbcOdbeDriver ConnTest8
Approach-9
As part of DriverManager class initialization it attempt to load jdbc
driver class that are there in fixed system property so driver will be
registered automatically.
Class contest
{
Public static void main(String args[]) throws IOException
{
Connection
con=DriverManager.getConnection(jdbc:odbc:oradsn,scott,tiger)
;
}
}
import java.sql.*;
public class ConnTest10
{
public static void main(String args[]) throws Exception
{
Connection
con=DriverManager.getConnection("jdbc:odbc:oradsn","scott","tiger");
if(con==null)
{
System.out.println("The conncetion is not establish");
}
else
System.out.println("the conncetion is establish");
}//>javac ConnTest9.java
}//>java Djdbc.driver=sun.jdbc.odbc.JdbcOdbcDriver ConnTest
Approach-10
}
}
Write a jdbc application that use stud
details based on the given start end rang of student no.
Select * from student where sno>=100 and sno<=400
//selectTest1.java
import java.sql.*;//for jdbc api
import java.util.*;//for Scanner
public class SelectTest1
{
public static void main(String[] args) throws Exception
{
//Read inputs
Scanner sc=new Scanner(System.in);
System.out.println("Enter start range of student no");
int stno=sc.nextInt();
System.out.println("Enter end range of student no");
int endno=sc.nextInt();
//register jdbc driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
//Establish connection with db s/w
Connection
con=DriverManager.getConnection("jdbc:odbc:oradsn","scott","tiger");
//create statement object
Statement st=con.createStatement();
//prepare SQL Queries
//select * from student where sno>100 and sno<=400
String qry="select * from students where sno>="+stno+" and
sno<="+endno;
System.out.println(qry);
//send and execute sql Query in db s/w
ResultSet rs=st.executeQuery(qry);
//process ResultSet
int cnt=0;
while(rs.next()!=false)
{
cnt=1;
System.out.println(rs.getInt(1)+" "+rs.getString(2)+"
"+rs.getString(3));
}//while
if(cnt==0)
System.out.println("No record found");
//close jdbc objs
rs.close();
st.close();
con.close();
}
}
Q: - Write a jdbc application to get student details based on the given
city name.
Q: - Write a jdbc app empno, ename, sal, job details of employee based
on the given dept no.
select empno, ename, sal, job from emp where deptno=10;
while processing resultSet use those index for column value in order
they stored in result set obj not in the order they are available in
database
While retrieving value from Resutlset record we can use
rs.getString() method if u dont know the data type.
We can call rs.getxxx(--) method to retrieve the value of record
either with cols name of cols index.
Assignment:-1
Write a program that returns students details based on given initial
characters of student Name?
Assignment: -2
3-5-2015
Ctrl+shift+o
Step-4 run the application
Right click in source file run as java Appuse run as button of the
menu bar.
To change JRE of the java project in eclipse
Right click on project build path libraries table remove existing Jre
Add library JRE System library next
Installed jreadd-standard vm next JRE home[c:\porgram files
(x86)\....--> select jdk finish.
xany
toString () method called on exception object just used to called
exception object that is raised.
printStack() method called on object elaborated details that is
raised.
When exception is raised in java method the stack memory of the
method will be filled up with exception related messages. TO print
those messages on console monitor we need to use printStackTrace()
method.
From jdk 1.7try with resource is intro where the resource in try will
be close automatically at the end of try without closing them explicitly.
Try(Scanner sc=new Scanner(System.in))
{
..
}
The Sc will be closed automatically at the end of try block.
Using try with Resource for jdbc code
Class InserTest
{
psvm()
{
try(
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver))
{
catch(exception e)
{
e.printStackTrace();
}
try(conncetion con=DM.getConnection(-,,);
Statement st=con.createStatement())
{
Int res=st.executeUpdate(delete from student where sno=10);
If(res==0)
Sop(record not delete);
Else
Sop(record deleted);
}//main
}//class
2015-03-07
Notepad, notepad++, editplus are editors
Eclipse, MyEclipse, NetBeans and etc, are IDEs
IDE provides total environment that is required for the
development and integration of the project.
Eclipse: Type: IDE for java environment
Vendor: Eclipse or
Version: 4.4 (Eclipse luna)
Open source (freeware)
To download s/w : wwweclipse.org
(as zip file: Extract zip file for installation)
Two flavors of Eclipse
3) JSE flavor (sdk)
4) Jee flavors
www.nataraz.in/software
xany
toString () method called on exception object just used to called
exception object that is raised.
printStack() method called on object elaborated details that is
raised.
When exception is raised in java method the stack memory of the
method will be filled up with exception related messages. TO print
those messages on console monitor we need to use printStackTrace()
method.
From jdk 1.7try with resource is intro where the resource in try will
be close automatically at the end of try without closing them explicitly.
Try(Scanner sc=new Scanner(System.in))
{
..
}
The Sc will be closed automatically at the end of try block.
Using try with Resource for jdbc code
Class InserTest
{
psvm()
{
try(
Class.forName(sun.jdbc.odbc.JdbcOdbcDriver))
{
catch(exception e)
{
e.printStackTrace();
}
try(conncetion con=DM.getConnection(-,,);
Statement st=con.createStatement())
{
Int res=st.executeUpdate(delete from student where sno=10);
If(res==0)
Sop(record not delete);
Else
Sop(record deleted);
}//main
}//class
Can be execute both select and non-select query by using single
method call Yes possible by using execute() method
This method return type is Boolean.
Prototype
.
Public Boolean execute(String qry) throws SQLException
This method returns true when it executes select SQL Query.
To get ResutlSet of this select SQL Query use getResultSet()
method.
This method returns values that represents number of records
that are affected because of this non-select Query use
getUpdateCount() method
For example application - ref-6 page no 24.
358
Working with execute method is not industry standard because it does
not give sql result directly more ever we need to call method separately
go gather sql query result (like getResultSet(), getUpdateCount)
Conclusion:
Use executeQuery(_) to send and execute select SQL QUERY
IN database s/w.
Use executeUpdate(-) to send and execute non-select sql
query in database s/w
Jdbc application to create database table in database s/w.
Note: - create table, drop table and alter table are non-select query.
So we should use executeUpdate () to send and execute these method
in sql query database s/w.
Satatement st=con.createStatement();
2015-03-10
There are 5 mechanisms/architectures to develop jdbc drivers based on
the rules and guide lines of jdbc technology
a) Type-1 driver (Jdbc odbc bridge driver)
b) Type-2 driver (Native API /Partly java driver)
c) Type-3 driver(Net protocol /All java Driver)
d) Type-4 driver(native protocol/ All-.java driver)
e) Type-5 driver(No nick name) (Not officially confirmed by Sun
Ms)
All odbc drivers and some jdbc drivers (type2) locate and
communicate with Db software by using vendor DB library.
In windows environment this vendor db library comes in the
form of .dll file along with Db software installation. (in oracle
it is oci.dll)
Every odbc driver and every vendor db library is specific to one
DB software.
Advantages
One Type-1 driver can interact multiple database software by
taking the support of odbc drivers , vendors db libraries
Since odbc drivers ,vendor db libraries are available for all db
software we can use this driver to interact with All Db software
This is built-in driver of jdk so there is no need of arranging this
driver separately.
Disadvantage
This driver performance is poor so not suitable for big
application.
Since vendor DB libraries are required at client side we cannot
use driver for untrusted applet to DB software communication.
This is not industry standards jdbc driver.
Suitable for testing apps
Removed from jdk from java 8 onward.
This driver must be arranged separately.
Type-2
Advantages:
1) This gives good performance compare to type-1, type-2
divers and suitable for large scale project
2) Totally developed in java so it is platform independent.
w.r to diagram
1) Server uses type-1/2 /3/4 driver to interact with database s/W
And create jdbc con objs in the jdbc con pool
2) Client app uses type3 driver interact with server and to get con
obj from jdbc con poo.
3) Client uses that con obj to create other jdbc objs and to develop
persistence logic
4) Client app releases the con obj back to jdbc con pool and that obj
becomes free to give service other clieents.
Proxy dummy item that represent present until real items come.
Proxy server talks with the database s/w on behalf of client
applications
Connection con=DM.getConnection(-,-,-);
b) Pooled connection(Gatherred from jdbc conn pool)
For related information of all jdbc drivers refer page no-8 to16
What is jdbc driver that u have used in project if your project is
standalone/desktop app talking with database s/w or two-tier app
running outside the server (webserver/proxy server) then use type4/5/
jdbc driver
If u r project web application, enterprise app, 3-tier app , ntier app running from the server then use type 3 with type4 or
type3 with type5 jdbc direr
Note: - Here type 4/5 driver will be user dot create jdbc con
objs in jdbc con pool and type3 driver will be used to get con
objs from jdbc con pool.
Q: -What is the difference between path and class path?
Ans: PATH:
It is OS command , can be used in all languages and technologies.
classpath
if java app uses new apis or third parties apis then the new
api/third party related directories or jar files must be added to
classpath in order to make java tools (javac ,java, .) recognizing
and using those apis.
It is a java command and cannot used outside the java.
Example
Problem:
User-defined API /third party api
E:/Demo1
|wish.java
Wish.jva
package con.nt;
public class wish
{
public String sayHello()
{
return good morning;
}//>javac d . wish.java
}
Main App
MainApp.java
Import com.nt;
Public class MainApp
{
Public static void main(String args[])
{
Wish w=new Wish();
System.out.println(w.sayHello());
}}
D:\work> javac MainApp.java(x)
Error: Can not find symbols com.nt, wish, sayHello
Solution: The address location of com.nt pkg(E:\Demo) folder to
ClassPath Environemnt variable.
ClassPath value=E:\Demos1;.
Ok(3).
D:\work>javac MainApp.java(success)
D:\work>java MainAp(success)
Jar file: jar archieve file(java level zip file)
Creating jar file representing apis
E:\Demos1>jar cf NtLib .
C =create jar file.
F=specify the jar file name.
To see content of the jar file
E:\Demos1\jar tf NtLib.jar
<JAVA_HOME>\JAR\LIB\EXT
FOLDER
jdk.
New values are not visible in old
command prompt
These values will be used by
(b)
Extension ClassLoader
<java_home>\jar\lib\ext
folder
Full path:- C:\Program Files\Java\jdk1.7.0_76\jre\lib\ext\[past here]
Value:
c:\orcleexe\app\orcle\porduct\10.2.0\server\jdbc\lib\odbc14.jar;<e
xisting value>;.
--ok(3).
Step3> Develop jdbc App using oracle thin driver
SelectTest.java
.
Connection con=DriverManager.getConnection
(jdbc:oracle:oci8:@xe,scott,tiger);
( jdbc:oracle) protocol
sid (xe)
If the subname is thin in the URL then the oracle thin driver
will be used to establish the connection.
If the subname is oci8 in the URL then the oracle oci driver
will be used to establish the connection.
Jar file added to the classpath are not visible to the projects
created in the IDE but the jar files added to the
java_home\jar\lib\ext folder are visible to the same.
To add jar file (like ojdbc14.jar) to the project of Eclipse IDE
use Right click on the project Build path add external
achieves browser and select the jar file (ojdbc14.jar)
While working with any jdbc driver we need to gather
a) Driver class name
b) Jdbc url
To create jdbc conn pointing to any database s/w we need 4
jdbc properties
a) Driver class name
b) Jdbc url
c) Database user name
d) Database password
The class name of jdbc object will change based on the jdbc
diver we use so we never specify them in our Apps but we
refer the object of those classes by using common jdbc api
interface reference variables.
Java.sql.Statement(I)
^
|extends
Java.sql.PreparedStatement(i)
^
| extends
Java.sql.CallableStatement(I)
There are 3 statement object in jdbc programming
a) Simple statement object
(it is the object of jdbc driver supplied java class that
implements java.sql.Statement(I));
b) PreparedStatement object
(it is the object of jdbc driver supplied java class that
implements java.sql.PreparedStatement object.
c) CallableStatement object
(it is the object of jdbc driver supplied java class that
implements java.sql.CallableStatement. object
2014-03-14
LoginAPP
Checks identity of a user by taking the given username and password
details .Also verifies them against Database table.
DB table in oracle
Saq> create table userlist(uname verchar2(20), pwd verchar2(20));
Sql> insert into userlist values(raja,rani);
Sql> insert into userlist values(king,kingdom);
Sql Query of the Application
Sql> select count(*) from userlist where uname=raja and pwd=rani1
Count(*)
0 (Invalid credentials)
LoginApp.java(refer page no-26 application no-8)
Java LoignApp
Username :raja - Password: hyd (wrong password)
Output : valid credentials (sqlinjection problem)
|com.nt
|StudentDAo.java
|MainApp.java
package com.nt;
import java.sql.*;
public class StudentDAO
{
Connection con=null;
public void makeConnection()
{
try{
Class.forName("oracle.jdbe.driver.OracleDriver");
//establish the connection
con=DriverMananager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","scott","tiger");
}//try
catch(Exception e)
{
e.printStackTrace();
}//catch
}//makeConneciton()
Statement st=null;
if(con!=null)
st=con.createStatement();
ResultSet rs=null;
if(st!=null)
rs=st.executeQuery("select * from students where sadd="+"'"+city+"'");
if(rs!=null)
{
while(rs.next())
{
System.out.println("rs.gtInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
}//while
}//if
//close objs
if(rs!=null)
rs.close();
if(st!=null)
st.colse();
}//try
catch(Exception e)
{
e.printStackTrace();
}
}//getStudntDetails
if(con!=null)
con.close();
catch (Exception e)
{
e.printStackTrace();
}
}//close connection
}//class
package com.nt;
public class MainApp
{
//call mehods
dao.makeConnection();
dao.getStudentDetails("hyd");
dao.closeConnection();
}//main
}//class
Assignment:
Q: = By using DAO style implementation get the emp details form emp
table who is having given nth highest salary.
When java app sends sql query to databse software ,the database engg of database s/w performs 3
operations on that SQL Query
1. Parse operation
2. Execution operation
3. Fetch operation
Parse-> In this operation the given query will be splited into tokens and the syntax of the query
will be verified by compiling SQL QUERY;
EXECUTE: - The Parsed Query will Optimized and will be executed in database software.
Fetch: - The results of executed SQL Query will be gathered from database software and will be
sent to java application client application.
Simple Statement obj sends raw/static SQL Query to database software , i.e given query goes
to database software directly wit out any conversions.
When use simple statements object to execute same SQL Query in database software for
multiple times either with same values or different values.
a) Same Query goes to database s/w for multiple times from java application.
b) Same query will be parsed in db s/w for multiple times.
c) Same query will be executed in db s/w for multiple times either with same values or diff
values.
d) Same query output will be fetched out from db s/w for multiple times.
Performing a), b) operation on same query for multiple times is unnecessary, But
performing c), d) operations on same query for multiple times is necessary, but we can
avoid a), b) operation happing for multiple times when we work with simple statement
object, Due to this we can say simple statement object is not suitable for executing same
query for multiple times with different values or same values.
Example:Railway Resrervation App that book 100000 tickets per day should execute same inser query for
`100000 times to maintains passenger details.
a) Same insert query goes to Db s/w from java app to database software for 1,00,000 times:
100000*0.1=10,000sec
b) Same insert query will be parsed in database software for 100,000 times:
1,00,000*0.1sec=10,000secs
c) Same insert queruy will be executed in database software for 1,00,000 times wither with same
or diff values:100000*0.1=10,000secs
d) Same insert query output will be fetched out for 100000 times : 100000*0.1=10,000secs
Performing a), b) operations on same for multiple times is unneccassary on same query, but this
cannto be avoided while working with simple statement object..
To overcome all these problem we need to work with percompiled sql query with support of jdbc
perparedSatement objcect.
Jdbc prepaearedStatement object represents this percompiled sql queryo of sb s/w being from java app and
this oject can be used
a) To assing multiple set of values to query params.
b) To execute query for multiple times either with same
values or diff values
c) To fetch the query results for multiples times.
Simple Statement object deals with static /raw sql
query where as PreparedStatement obj with precompiled sql query.
The above Railway ticket reservation example with
PreparedStatement obj
a) Insert query oges to Db s/w from java app only for one
time
:1*0.1=0.1 sec
: 1*0.1=0.1 sec
1,00,000*0.1=10,000secs
Ps.setString(3,hyd);
Step:-4) Execute the above pre.compiled sql query of
database s/w.
Int result=ps.executeUpdate();
Step5) Process the result.
If(result==0)
Sop(record not inserted);
Else
System.out.println(Record inserted);
Step: -6) To execute the above query for multiple with diff
values repeat step3 to step 5 for multiple times.
Step:-7) close jdbc object.
Here we need to execute same insert SQL Query with diff values
for multiple times, for this we need to use per-compiled SQL
Query with the support of jdbc PreparedStatement object.
Referr application
IN THE development logic it is always recommended to sql query
}
in the above code select * form student will not be executed but select
* from emp will be executed as static SQL Query.
(Vvi)
PreparedStatement
1. Deals with pre-compiled sql
query (dynamic query)
2. Suitable for executing query for
multiple times either with same
Why simple Statement object raises sql injection problem and why sam
problem does not raise in PrepasredStatement.
Simple Statement obj makes the DB engine of Database software to
compile sql query with input values, so the special sql instruction (like
--) that are given along with input values participate in query
records.
Step-1) Launch mysql prog
Start mysql mysql 5.5 command line client
Password (root) which is choosen during installation
Setp2) create Logical DB NTDb1
(protocol)
Datatype
len
Pid
Int
Assignment
Develop jdbc app that transfers the record from oracle db table to
my sql table.
2015-03-19
date value then jdbc driver inserts the date value in the
pattern it supported by underlying database s/w.
Example application to retrieve different date pattern value and insert
them in database table.
Refer app-10
Person_tab(in oracle)
Ask data of birth from end user and calculate his age.
To retrieve date values from DB table we can use either
Simple Statement object or PreparedStatement object.
To retrieve Date values form jdbc ResultSet object we can use
rs.getDate(-) method.
(1)
(2)
(3)
(4)
(5)
import java.util.*;
public class AgeCalApp
{
public static void main(String args[])
{
float age=(float)ms/(1000.0f*60*60*24*365);
System.out.println("Age" +age);
}
}
Q: - Write a jdbc application to copy records from students
records form MySQL to student table of oracle.
PreparedStatement object.
In one application we can have multiple jdbc connection
object, Statement objects ,ResultSet objects.
file:///E:/Javaprogramming/Naresh/mysql/swing/SetFromSwing.java
3. Write a jdbc application to write the records of database table
to text file or html file
package com.nt;
Class.forName("com.mysql.jdbc.Driver");
Connection
oracon=DriverManager.getConnection("jdbc:oracle:thin:laocalhost:152
2:orcl","scott","tiger");
Connection
mysqlcon=DriverManager.getConnection("jdbc:mysql:///NtDb6","water",
"water");
//create statement object
Statement st=mysqlcon.createStatement();
{
//get each records from mysql db table
int no=rs.getInt(1);
String name=rs.getString(2);
String addrs=rs.getString(3);
//set the above values to qury paames
ps.setInt(,no);
ps.setString(2,name);
sp.setString(3,addrs);
}//while
System.out.println("records are copiied");
rs.close();
ps.();
mysqlconn.close();
myoracon.close();
}
}
select * from (
select empno
, sal
, dense_rank() over (order by sal desc) as rnk
from emp)
where rnk = 5
/
select * from (select empno,ename,sal,row_number() over(order by sal desc
nulls last) rnm
from emp) where rnm<=10
2015-03-23
Retrieving large object for this we can either use simple statement
or PreparedStatement object.
To read clob values from ResultSet we can either
rs.getBinaryStram(-) or rs.getBlob(-) method.
To read clob value form ResultSet we can use either
rs.getCharacterStream(-) or rs.getClob(-) method.
2015-03-31
In Real time the application will be converted .exe file in order to
release them to client organizations
These .exe file can be executed in any system even though java is
not available in that system.
j2e_free.zip file
4. Use J2E tool to convert the above NtAp.jar file to an exe file.
Launch jar to exenextbrows jar (e:\app\demoexe\ntapp.jar
Jre version min 1.6 max 1.7
Target system windows
getXXX()
close()
getRow() to know the current position of cursor/record pointer in
ResultSet.
getxxx(-)
getRow(-)
close()
afterLast() Moves the cursor to ALR Position
beforeFirst()
first()
last() moves the cursor to last record
isFirst() checks weather cursor is there in first record or not
isLast() Checks weather cursor is there in last records or not
absolute(+/-n)
relative(+/- n)
Exhusted.
Creating scrollable ResultSet object by using PreparedStatement object.
PreparedStatement ps=con.prepareStatement(select * from
student,ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDA
TABLE);
ResultSet rs=ps.executeQuery();
In the above application we need to move cursor in ResultSet
randomly based on the button that are clicked for this we need to
take Scrollable ResultSet object.
Event: ActionEvent
Free IDE
To download s/w: www.Oracle.com (or) www.netbeans.org
App 19 by using NetBean IDE
Step-1) create java project in NetBean
Filenew project java java application next(project
name)
finish
{
Connection con;
PreparedStatement ps;
ResultSet rs.
}
makeConnection();
}
ps=con.prepareStatement("select * from
Student",ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
rs=ps.executeQuery();
}//try
catch (Exception e)
{
}
e.printStackTrace();
rs.first();
jTextField1.setText(rs.getString(1));
jTextField2.setText(rs.getString(2));
jTextField3.setText(rs.getString(3));
}//try
catch (Exception e)
e.printStackTrace();
}
Step-9) write following code in JButton2ActionPerformed(-) for next
button.
Try
{
if(!rs.isLast())
{
rs.next();
}
rs.first();
jTextField1.setText(rs.getString(1));
jTextField2.setText(rs.getString(2));
jTextField3.setText(rs.getString(3));
}//try
catch (Exception e)
{
e.printStackTrace();
}
Step-10) write following code in JButton3ActionPerformed(-) for
previous button.
Try
{
if(!rs.isFirst())
{
rs.previous();
}
rs.first();
jTextField1.setText(rs.getString(1));
jTextField2.setText(rs.getString(2));
jTextField3.setText(rs.getString(3));
}//try
catch (Exception e)
{
e.printStackTrace();
}
jTextField2.setText(rs.getString(2));
jTextField3.setText(rs.getString(3));
}//try
catch (Exception e)
{
e.printStackTrace();
Statement
st=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,Result
Set.CONCUR_UPDATABLE)
ResultSet rs=st.executeQuery(Select * from student);
By using Updatable ResultSet we can perform insert,update,delete
To delete record
rs.absolute(2);
rs.deleteRow();//deletes 2nd record.
For example application on updatable ResultSet application -21
page no-43.
Type one driver support updatable ResultSet.
The oracle thin, oci drivers support updatable ResultSet only
Metadata: -
2015-04-03
along with the column name refer app-25 of the page no46,47
ParameterMetaData
2015-04-04
getParameterTypeName(-)
getParameterTypeName(-)
siSigned(-)
isNullable(-)
getScale(-)
getDecimal(i)
and etc
Most of jdbc driver including type-1 driver, oracle thin driver, oi
dirver does not support parameterMetaData because they are not
providing any implementation class for this interface.
Page-47 application-26.
Properties files:-
The Text file that maintains the entries as key values pairs is
called text properties file.
Example: DBDetails.properties
#driver=oracle.jdbc.driver.OracleDriver
url=jdbc:odbc:thin:@loacalhost:1522:orcl
user=scott
password=tiger
java.util.Properties class which is a sub class of java.util.Hastable can
load element values from given text properties file.
//locate properties file
2015-04-07
BatchUpdation using Simple Statement object
Step-1) create Statement object
Statement st=con.createStatement();
Step-2) add batch of non-select queries to
statement object.
St.addBatch(insert into student
values(901,raja,hyd));
St.addBatch(delete from student where sno>100);
St.addBatch(update student set sad=vizag where
sno<=50);
Note: - Any number of queries can be added to
batch, but select query should not be added.
Step-3)Execute the Batch
Int res[]=st.executeBatch();
Conclusion:
executeUpdate(-) :for non-select queries execution
executeQuery(-): for select queries.
execute(): for calling pl/sql procedure/functions
executeBatch(): for batch updatation.
For example of batch processing app-30 page-49.
Transaction management
The process of combining related operations into
single unit and executing them by applying do
every thing or nothing principle is called
transaction management(tx)
Batch processing
Tx deals with 3
operations
a) Begn tx
b)
perform operations
..
c) Commit or rollback.
Begn Tx is nothing
Commiting Tx is
{
Flag =false;
Break;
}
}
If(flag==false)
{
Con.rollback();
System.out.println(Tranction (tx is rollback );
}
Else
{
Con.commit();
System.out.println((transaction (tx) is committed);
}
Transfer money operation is the combination of two operations
a) With draw amount from source account
//execute batch
int res[]=ps.executeBatch();
boolean equalsIgnoreCase(String anotherString)
Compare this string to another string, ignoring case
considerations.
Save point
The final outcome of transaction is either committing results or roll
backing result if u want ot perform both commit or rollback acticity in
a transaction then we need to use save point.
Save point is a point in a transaction up to which we can rollback.
Begin Tx
Operation-1
Operation-2
Save point p1
Operation-3
Operation-4
Rollback to p1
Commit Tx
Here operation-1, operation-2 will committed and operation-3
and operation-4 will be rolledback.
There are two types of save point
1. Named save point (programmer gives name)
2. UnNamed save point(DB s/w gives name internally)
To create Save Point
SavePoint sp=con.setSavePoint(mysp);
Setp-1) create MS-excel work book and work sheet as shown above
E:\apps
|------college.xls
|----sheet1
Step-2)create dsn for ms-excel
Step-3) develop the application
import java.sql.*;
import
public class ExcelTest
{
public static void main(String args[]) throws Exception
{
Class.forName("sun.jdbc.JdbcOdbcDriver");
Connection
con=DriverManager.getConnection("jdbc:odbc:xlsdsn");//xlsdsn
Statement st=con.createStatement();
//send and sql query
ResultSet rs=st.executeQuery("select * from [Sheet1$]);//sheet1$->
sheet name as table name
//process the result
while(rs.next())
{
System.out.println(rs.getInt(1)+""+rs.getString(2)+""+rs.getString(3));
}
int resutl=st.executeUpdate("insert into[sheet1$] values(901,'raja','hyd');
st.close();
rs.close();
con.close();
}
}
//textTest.java
import java.sql.*;
public class TextFileAsDatabase
{
public static void main(String args[]) throws Exception
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection
con=DriverManager.getConnection("jdbc:odbc:txtdsn");//txtdsn--dsn name
//crate staement
Statement st=con.createStatement();
//execute query
ResultSet rs=st.executeQuery("select * from file1.csv");//file1.csv--file
name as database table
//process the result set
while(rs.next())
{
System.out.println(rs.getInt(1)+""+rs.getString(2)+""+rs.getString(3));
}
rs.close();
st.close();
con.close();
}
}
We can use one statement object to send and execute multiple sql
queries in database s/w one after another.
Postgresql
Type: DB s/w
2015-04-11
Version: 9.x
Vendor:- Enterprise DB
In one physical Database s/w we can create multiple logical DBs on one per
project basis.
integer
double precision
Class.forName("org.postgresql.Driver");
//establised the connection
Connection
con=DriverManager.getConnection("jdbc:postgresql:NtDB2","postresql",root");
//create statement object
Statement st=con.createStatement();
//execute query
con.close();
number
Sname
text
Sad
text
ramesh
hyd
102
raja
vizag
Example application to interact with MS-Access using type-1 driver: Step-1) create dsn for Ms-Access driver.
Launch odbcas32.exeuser dsn add
accdbaccdsnselect
e:\app\college.accdbok
Step-2) developed java application with type-1 driver.
//AccessTest.java
import java.sql.*;
//register driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection
con=DriverManager.getConnection("jdbc:odbc:accdsn");
}
//accdsn
RowSet
To send java object over the network the object must be taken as
serializable object . For this the class of object must implement
java.io.Serilizable(I).
Java Bean is java class that following standards.
a) Class must be public
b) Class must implement java.io.Serializable
c) Class should have private properties(members)
d) Class should have 0-parameter constructor
e) Every property should have setter and getter methods
public class Student implement Serializable
{
//poperty
private sno;
public student()
{}
//setters and getters
public void setSno()
{
this.sno=sno;
}
public int getSno()
1.
2.
3.
4.
5.
{
return sno;
}
}//end class
Jdbc ResultSet are not srilizable object so we can not send them over
the n/w.
ResultSet can not created through Bean style programming(settes and
getters)
To overcome these problem use jdbc 2.0 feature Rowset. The benefits are
a) Most of the Rowsets are serilizables.
b) Can be created easily through bean style programming.
Resultset object are connected object that means to process ResultSet
our application should maintain connectivity with database s/w even
after crating the ResultSet object.
We can see Row Set as connected object or disconnected object.
Disconnected object means we need not to have connection with DB
s/w to process Row Set once the Rowset has been created.
Rowset object means it is the object of driver supplied java class that
implements javax.sql.RowSet(I). This is sub interface of
java.sql.ResultSet(I).
There are five type of Rowsets.
Jdbc RowSet (Connected RowSet)
CachedRowSet (disconnected RowSet)
WebRowSet (disconnected RowSet)
Join RowSet (disconnected RowSetora)
Filtered RowSet (disconnected RowSet)
Oracle corp has given 5 classes supporting these 5 RowSets
1. OracleJDBCRowSet
2. OracleCacheRowSet
3. OracleWebRowSet
oracle.jdbc.RowSet packgae
4. OracleJointRowSet
5. OracleFilterdRowSet
Jdbc RowSet
It is a connected Rowset.
Modification done in the RowSet will be reflected to table directly
without any special method.
It is more like regular jdbc ResultSet object that allows bean style
programming.
This RowSet is not a serializable object.
For example application -28 page -48
cachedRowSet
It is a disconnected RowSet
It acts as a Buffer/cache after getting records from DB table RowSet.
We can manipulate/process this RowSet even though connectivity with
DB s/w is not there, but we should call acceptchanges() method
explicitly to refect the modifications back to DB table.
Except JDBCRowSet all RowSet are serializable objects.
For example application -27 of page no-47.
While developing pda (personal digital app) for lic agent we should we in
position to process the data without database connectivity, we use
cache RowSet.
crowset.setReaOnly(false);
//insert record
crowset.setReadOnly(false);
crowset.moveToInsertRow();//empty row in RowSet
crowset.updateInt(1,001);
crowset.insertRow();//inserts record
crowset.acceptChanges();//connects back to DB
//delete record
crowset.absolute(2);
crowset.deleteRow();
crowset.acceptChanges();
//update record
crowset.absolute(3);//points to 3 row in RowSet
crowset.updateString(2,'yyy');
crowset.updateRow();
crowset.acceptChanges();
WebRowSet
It is same as CachedRowSet but allows renders output S mcl (db table
records) and also inputs as xml.
In web environment if we want to Db table records to xml file content
then use webRowSet.
In webServices two dissimilar application talk with each other by passing
data in the form of xml. To get that data from dB table and to convert
into xml use webRowSets.
For example appl ref ap-29 page-48