java


How to pass List in sql query


I have of values (1, 2, 3, for example), and I want to pass that list to a SQL query:
"select name from tbl where id in" + list
How might I achieve this?
I see in your reply to a comment that you're using HQL. If that's the case, the Hibernate folks make this one easy for you, in the query, just specify:
where id in (:ids)
and then use setParameterList("ids", list) passing your list. Hibernate will do all the expansion for you!
you have to put your list directly to sql statement
example:
String sql="select name from tbl where id in ("+StringUtils.join(list, ',')+")";
Statement st=connection.createStatement();
st.execute(sql);
The SQL syntax is:
select name from tbl where id in (1,2,3)
All you have to do is build the comma separated list of items and insert it in the string.
Oh and the obligatory sql string building warning: don't!
Pass the list in as a comma seperated list and use a split function to split it into a temporary table variable.
CREATE FUNCTION dbo.Split (#sep char(1), #s varchar(512))
RETURNS table
AS
RETURN (
WITH Pieces(pn, start, stop) AS (
SELECT 1, 1, CHARINDEX(#sep, #s)
UNION ALL
SELECT pn + 1, stop + 1, CHARINDEX(#sep, #s, stop + 1)
FROM Pieces
WHERE stop > 0
)
SELECT pn,
SUBSTRING(#s, start, CASE WHEN stop > 0 THEN stop-start ELSE 512 END) AS s
FROM Pieces
)
I tried the solution provided by Farmour. Its simple, efficient & works.
I modified it lil bit according to my need...& also tried debugging to ensure its formatted exactly the way I want.
public static String sqlFormatedList(List codeList){StringBuilder sb = new StringBuilder();
sb.append("(");
for (String str : codeList){
sb.append("'"+str+"',");
}
sb.deleteCharAt(sb.length() -1);
sb.append(")");
return sb.toString();
}
Analysis in brief :
Input Params : [ABC,MNP,XYZ]; as List of Strings of Java format
Output : ('ABC','MNP','XYZ'); as String to be used in SQL query.
sqlFormattedString = ('ABC','MNP','XYZ');
This above o/p string goes in this query.
select * from tableName as tn where tn.code in sqlFormattedString;
PS : codeList in Parameter List is java.util.List
it depends on how you are constructing your sql. If you are constructing it yourself (bad idea) you need to do make the sql look like -
... where id in (1,2,3)...
Since in your comment you specify hibernate hql, something like -
Query query = session.createSQLQuery("from User where id in :ids ");
query.setParameter("ids", idsList);
List list = query.list();
should get you started. Note User is the name of the Object you mapped to the table you want to query.
String sqlQuery = "select name from tbl where id in" + sqlFormatedList(list);
private String sqlFormatedList(List<Integer> list){
StringBuilder sb = new StringBuilder();
sb.append("(");
for (Integer i : list){
sb.append(i+",");
}
sb.deleteCharAt(sb.length() -1);
sb.append(")");
return sb.toString();
}

Related Links

How to Split String with delimited string “#|#” [duplicate]
Android - Cannot get priority of IntentFilter
add multiple texts to JTextPane, and not replace each text with another
tomcat 8 in Eclipse Luna failed to start : Error with directory [C:\Program Files\Eclipse\eclipse\lib]
How to list All Directories in file along with their sub directories? [duplicate]
RestAssured Outh login isuue to Twitter
Initialize array of custom class
Creating a “Shell” for fragments in android
Peoples weight Decmal Format
Rest-Assured. Random “Cannot invoke method getAt() on null object” Error when running multiple test suites in Maven
Connection does not correctly set catalog using HikariCP
Issue with tracing down the array in Java recursion function
how to scroll my screen
IllegalArgumentException when writing Dataframe to Hive table
converting the contents of memory from int to char
How to resolve a custom option in a protocol buffer FileDescriptor

Categories

HOME
fluentd
malloc
amazon-ecs
binary-tree
alpha
in-app-purchase
slick-slider
session-variables
facebook-php-sdk
volttron
nstableview
apache-cayenne
usergrid
leiningen
after-effects
jquery-ajaxq
functional-testing
css-animations
microsoft-r
java-7
sqlcipher
javacv
pepper
poltergeist
phpfox
fgetcsv
webkitspeechrecognition
c++-amp
google-qpx-express-api
grails-3.1
http-referer
simplexml
dartium
space-complexity
withings
ansible-playbook
greenrobot-eventbus
awt
scorm
chain-builder
prolog-setof
hls.js
dropbox-php
fancybox-2
rdfs
yii2-extension
brightcove
worker-thread
composite-key
orthogonal
ableton-live
thrust
nsfilemanager
plottable.js
disque
ora-00900
google-places
mutation-observers
retina
jqgrid-formatter
pundit
tableau-online
responsive-images
angularjs-ng-click
rdtsc
zend-route
has-many-through
starcluster
uitouch
elliptic-curve
yorick
resty-gwt
prettify
gridfs
listings
pygit2
flashvars
kyotocabinet
factory-method
isnullorempty
coderush
broken-links
frameset
manchester-syntax
ocx
ticoredatasync
wse3.0
spring-portlet-mvc
eclipse-templates
stage
deobfuscation
psi
xtype
telerik-scheduler
sortable-tables
preference
database-management
pascal-fc
mdac

Resources

Database Users
RDBMS discuss
Database Dev&Adm
javascript
java
csharp
php
android
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App