Statements In JDBC JDBC Interview Questions JDBC Statements PreparedStatement and CallableStatement JDBC Technology Call Stored Procedures

Statements In JDBC

 

Statements  in JDBC are carrier for sql queries in JDBC.  Statements in JDBC are obtained from connection objects.

Connection is the handle for the session between JDBC and Database server.Without connection object we cannot have a statement object and without statement object,sql queries cannot be run at the database server side from the JDBC code.

There are three types of statements in JDBC.These are as follows :

1.Statement

2.Prepared Statement

3.Callable Statement

 

1.Statement : These statements are used to execute queries like select statements at the server side. Every time a statement is run it is compiled at the server (database side),it is compiled at the server side and run.

The code looks like this :

Class.forName("driver class");
Connection conn = DriverManager.getConnection("connection string","username","password");
String sql = "select * from tablename";
Statement st  = conn.createStatement(sql);
st.executeQuery();

 

2.Prepared Statement : These statements are used where we have to execute same query multiple number of times with small changes like update value.In such cases we do not need to compile the query again and again at the server side but we need to compile he query once and keep executing again and again at the the server side.Thus,prepared statements help in this case as these are precompiled statements which can be executed ample times thus saving time.

 

The code looks like this :

Class.forName("driver class");
Connection conn = DriverManager.getConnection("connection string","username","password");
String sql = "insert into tablename values (?,?,?)";
PreparedStatement pst  = conn.prepareStatement(sql);
pst.setString(1,"java");
pst.setInt(2,3);
pst.setFloat(3,3.14);
pst.executeQuery();

 

The ‘?’ are placeholders to feed the value to the precompiled statements.setXXX methods are used to set the values to the placeholders depending upon the  data type at the server side.In the code pst.setString(1,”java”),1 denotes the first place holder.

 

3.Callable Statement : These statements are used to execute stored procedures and function at the database server side.

The code looks like this :

Class.forName("driver class");
Connection conn = DriverManager.getConnection("connection string","username","password");
String sql = "{? = execute procesdureorfunctionname(?,?)}";
CallableStatement cst  = conn.prepareCall(sql);
cst.registerOutParameter(1,java.sql.Types.String);
cst.setString(2,"java");
cst.setInt(3,3);

cst.execute();
String str = cst.getString(1);

 

Number of View :911

Tags: , , , , , , , , , , ,

  1. No comments yet.

SetPageWidth
Content Protected Using Blog Protector By: PcDrome.

Mahol Dot Org is Stephen Fry proof thanks to caching by WP Super Cache