Pass a list of elements, separated by commas and single quotes, to the syntax of an SQL IN using JAVA code


A crude example of what I need to have an idea is the following:

 SELECT name,last_name 
 FROM employees    
 IN('sstan','Ivan Botero','Stefan Nolde','Jose Javier 
 Segura','jose','Miguel Osorio','etc');

That is to say that by means of connection with JDBC, to have a query to which a list of elements passes to him within IN by means of code java. concatenating and separating commas and single quotes with each element of the list.

Another crude example (since I can not place the query in question but for example terms serves as a reference) , it would be something like the following in java:

String Query = "SELECT name,lastname "
+"FROM employees "
+"WHERE lastname  IN ("+ lista_con_nombres.toSting() +") " + 
asked by Ikabod 24.08.2016 в 22:30

1 answer


The solution was the following:

In the first append concatenate single quotes, in the second append concatenate the element, in the third append concatenate the last single quote, in the fourth append concatenate the comma for the next element.

StringBuilder sb = new StringBuilder();

for (int i = 0; i < lista_con_nombres.size(); i++){  
    sb.deleteCharAt( sb.length() -1 ).toString();

Here I delete the last comma in the string since it is not necessary.

 sb.deleteCharAt( sb.length() -1 ).toString();

To consider

It should be noted that I'm sticking to the question rather than using parameters to avoid SQL injection, each user knows how your application works and how to avoid this type of things.

answered by 25.08.2016 / 20:47