• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Dynamic SQl - PreparedStatement

 
Ranch Hand
Posts: 83
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi All,

I have the below requirement in my project. The project uses dynamic sql in its queries in the following way.

sqlQuery = sqlQuery + " AND GROUP IN ("+ userRole.toString().trim() + ") ";

userRole is StringBuffer whose value would be 'admin','inq'

Now the query hard codes the value, i want the value to be set at run time using PreparedStatement.

I tried modifiying the above query as below.

StringBuffer userRole = new StringBuffer(" ");
userRole.append(" ' ");
userRole.append("admin");
userRole.append(" ', ");
userRole.append(" ' ");
userRole.append("inq");
userRole.append(" ' ");
sqlQuery = sqlQuery + " AND GROUP IN ( ? );
stmt = conn.prepareStatement(sqlQuery);
stmt.setString(1,userRole.toString().trim());

But the problem here is while runtime, the below value is considered as a "single String" instead of two different strings due to which my query is failing.

'admin','inq'

Can someone help me out on this? I need the value to be two different strings when i am setting it dynamically.
 
Ranch Hand
Posts: 128
Hibernate Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Why did you decide to hard code the values?
 
Ranch Hand
Posts: 75
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The easiest way is to store your IN values in an array instead of StringBuffer. You simply build your query with bind variables like :1 to :n (n = length of array). Then you would need to bind the values of the array to the SQL query in a loop.

 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic