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 call a variable FROM another method INSIDE the main the method to perform a math calculation
How to do lambda operations with stream?
How use the class MyBluetoothService in the Android bluetooth documentation
Angular2 and ng2-table: jobs:29 Error: (SystemJS) require is not defined
Using stanford I want to get all the adjectives and nouns in my sentence after doing the pos tagging and store them in separate strings
why isnt a thread waiting for an object lock responsive to interruption?
Howto handle moving Items in OSMDroid maps
Change Android API
How can I get the server filepath of the JSP from a servlet?
ArrayList is emptied (Android Studio (Google Maps API))
Can you convert a Model to a ModelAndView?
Gradle wsdl generating
Spring Oauth2 Authorization_Grant - cannot access resources after token - User Anonymous
FirefoxDriver() is not working - Selenium,Java
Find shape within rows of characters-Java
Android: Function returns the value before the value is updated from firebase help me out to return the updated value

Categories

HOME
google-chrome-extension
winforms
pypi
layout
iterator
raspberry-pi
read-eval-print-loop
getelementsbytagname
jpeg
multiple-records
imacros
rascal
modelica
zend-framework3
quartz-scheduler
ghc
undefined
ab-testing
excel-vba-mac
nas
graphicsmagick
zurb-foundation-6
restful-authentication
lcd
autosys
angular2-aot
xpages-ssjs
centos6.5
facebook-access-token
brunch
virtualdub
assistant
saas
dbclient
google-cloud-nl
file-rename
socialengine
phonegap
titanium-mobile
wallpaper
mmenu
mpmediaquery
simplexml
bitbucket-pipelines
swift3.0.2
espeak
starteam
unspecified
impersonation
gulp-sourcemaps
reportingservices-2005
jvm-languages
sencha-touch-2.3
dotcover
termination
komodoedit
multipeer-connectivity
theming
diagnostics
watchconnectivity
time-and-attendance
passport-google-oauth
adxstudio-portals
autorest
disque
hexdump
goose
independentsoft
pervasive-sql
jqgrid-formatter
drawbitmap
0xdbe
composite
angular-local-storage
jsapi
truevault
apache-commons-net
npapi
nsmutabledictionary
block-device
network-interface
client-side-templating
flask-cors
openexr
undefined-reference
algebraic-data-types
imdbpy
prettify
floating-point-precision
aqtime
web2py-modules
odata4j
jplaton
selected
bluepill
frameset
automount
pendrive
nsdatecomponents
whoosh
fireworks
coredump
jmock
datareader
revisions
modelstate
eqatec
commodore
windows-live-messenger

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App