Hi I am trying to learn JDBC. and here is my question:-
What is the Use of PreparedStatement
in JDBC Because We can achieve the same effect by using createStatement();
too.
I mean if there is a query like:
Select * from tbl_name where id = somevalue
Then We can achieve it by both PreparedStatement
and createStatement()
. As follows:
Using CreateStatement()
:
try {
DataInputStream dis=new DataInputStream(System.in);
System.out.println("Enter id :- ");
int id=Integer.parseInt(dis.readLine());
String q="Select * from tbl_name where id="+id;
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(q);
while(rs.next()) {
//fetching part
}
} catch(Exception ex){ ... }
Using PreparedStatement
:
try {
PreparedStatement preStatement=conn.prepareStatement("Select * from tbl_name where id=?");
DataInputStream dis=new DataInputStream(System.in);
System.out.println("Enter id:- ");
int id=Integer.parseInt(dis.readLine());
preStatement.setInt(1, id);
ResultSet result = preStatement.executeQuery();
while(result.next()){
// fetch the data
}
}catch(Exception ex){ ... }
As both of these programs are capable of doing the same task.
- Why there is provision of two different Methods? Also looping seems to be easy if avoid repeatation is the answer.
- Can any one tell me which one is good to use ?
- what is the provision of each of them?
- What is the difference between them, and which one optimizes the code?