wood burning stoves*
The moose likes JDBC and the fly likes using prepare statements Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Databases » JDBC
Bookmark "using prepare statements" Watch "using prepare statements" New topic
Author

using prepare statements

Peter Warde
Ranch Hand

Joined: Aug 18, 2004
Posts: 71
I have a prepared statement that has a sql query such as

SELECT *
FROM table1
WHERE name IN( ? )

and I have an array String [] names.

How do I pass the array names as a parameter to the prepared statement?
Sathya Narayanan Natarajan
Greenhorn

Joined: Mar 15, 2005
Posts: 2
Hi

From the String[] Array, Construct a Comma-Separated String Of Names in the following format ,

'Name1','Name2','Name3'

The following code will help you get a Comma-Separated-String of Names

String param = stringArray[0];
for (int i = 1; i<stringArray.length; i++) {
param += stringArray[i];
}


Then, just set the param in the statement as follows,

preparedStatement.setString(1,param);
Then run the query.

Hope this helps you,
Thanks.
Sathya
James Carman
Ranch Hand

Joined: Feb 20, 2001
Posts: 580
Actually, I don't think you can do that, set the list of strings for an "in" condition. You might have to build your SQL by hand then. Just make sure you escape any single quote characters.


James Carman, President<br />Carman Consulting, Inc.
Ilja Preuss
author
Sheriff

Joined: Jul 11, 2001
Posts: 14112
Moving to JDBC...


The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Lu Battist
Ranch Hand

Joined: Feb 17, 2003
Posts: 104
This will work better, but if you expect nulls in the stringArray
you may need to test for that and use the preparedStatement.setNull(...) method.


[ March 16, 2005: Message edited by: Lu Battist ]
 
 
subject: using prepare statements