aspose file tools
The moose likes JDBC and the fly likes Bind variables multiple times in Prepared Statement Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Databases » JDBC
Reply Bookmark "Bind variables multiple times in Prepared Statement" Watch "Bind variables multiple times in Prepared Statement" New topic
Author

Bind variables multiple times in Prepared Statement

Dhruv Chandna
Greenhorn

Joined: May 16, 2008
Posts: 5
Hi,
I have a beginners question. I have the following piece of code that iterates through a list and then binds a variable to a prepared statement and executes the query. Please let me know if it is appropriate to use PreparedStatement like the way I have done.

List<Integer> list = new ArrayList<Integer>();
list.add(1);
list.add(2);

String query = "select name from emp where emp_no = ?";

Connection conn = <someconnection>;
PreparedStatement pstmt = conn.prepareStatement(query);
ResultSet rSet = null

for(Integer id: list){
pstmt.setInt(0, id);
rSet = pstmt.executeQuery();
while(rSet.next()){
//Do something.
}
}

Also, I do not want to use "IN" in the select query.

Thanks a lot.
FeatherHead
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 56168
    
  13

"FeatherHead", please check your private messages for an important administrative matter.


[Smart Questions] [JSP FAQ] [Books by Bear] [Bear's FrontMan] [About Bear]
Sagar Rohankar
Ranch Hand

Joined: Feb 19, 2008
Posts: 2896
    
    1

Yes, you can clear out the set parameter once you are finished with using them , like here



Also, I do not want to use "IN" in the select query.


I dont get it, Whats your point?

And pl change your name as per JavaRanch naming policy !


[LEARNING bLOG] | [Freelance Web Designer] | [and "Rohan" is part of my surname]
Dhruv Chandna
Greenhorn

Joined: May 16, 2008
Posts: 5
Thanks a lot.

By not using "IN" in the query i meant that i did not want to modify my query in order to execute the prepared statement just once.

I've changed the display name. Sorry for not abiding by the ranch rules.
Jeanne Boyarsky
internet detective
Marshal

Joined: May 26, 2003
Posts: 26168
    
  66

Dhruv,
Your approach is fine. Note that you will have a network trip for each query. If you have a large number of ids and the database is on another machine, this could be a performance problem.


[Blog] [JavaRanch FAQ] [How To Ask Questions The Smart Way] [Book Promos]
Blogging on Certs: SCEA Part 1, Part 2 & 3, Core Spring 3, OCAJP, OCPJP beta, TOGAF part 1 and part 2
 
I agree. Here's the link: http://zeroturnaround.com/jrebel/download
 
subject: Bind variables multiple times in Prepared Statement
 
Similar Threads
display all items from a list
Dynamic column selection in prepared statement?
slow query speed -- an Indexing problem ?
SELECT * FROM TESTTABLE WHERE ID IN (?)
How to know the type at runtime?