Saturday, March 28, 2009

Using Prepared Statement

Using Prepared Statement Object

There are several situations where you want to query database according to some condition.For Example if you want to list all employees having salary greater than 10,000,then you will provide condition which states salary must be greater than 10,000.

The query would be :-

"select * from emp where salary>10000 "

The above query will list all employees having salary more than 10,000.
For providing any condition you must provide some condition using Comparison Operators.
To make it possible ,you will have to prepare a query statement ,that receives an appropriate value in the where clause,at run time.

The PreparedStatement object allows you to execute parametrized queries.The PreparedStetement Object is created using the preparedStatement() method of the Connection Class.Like following:

stat=conn.preparedStatement("select * from emp where salary=?");

The preparedStatement() method of the Connection object takes SQL statements a parameter .The SQL Statement can contain placeholders that can be replaced by INPUT parameters at runtime.

Note:-The "?" symbol is a placeholder that can be replaced by the INPUT parameters at runtime.

For replacing a placeholder use following:

stat.setInt(1,10000);
result=stat.executeQuery();
result.next();

Here we are setting value of salary in the query through "setInt()" method.
This value is set to "?" and query is passed further to execute.

GoTo:-
Home
JDBC Architecture
Configuring ODBC Sources
Connecting to database
Querying Database
Using ResultSet Object
Deatailed JDBC Example-Statement Object

0 comments:

About This Blog

This Blog is all about Java and programming.This blog is written by Vaibhav Pandey .He is a Computer Science Graduate .You can contact the author at javatute@gmail.com for any suggestion or Query.You can also contact the author for advertising on this blog.All the material presented here is the property of author and its reproduction in any form is strictly prohibited.

Disclaimer:-Download links provided here are not of author in any means.These are found over the Internet.
Page copy protected against web site content infringement by Copyscape

  © Blogger templates The Professional Template by Ourblogtemplates.com 2008

Back to TOP