sTg sTg - 23 days ago 8
Java Question

using single quotation for a value in java to be sent to proc using sql query?

I have a few

String
values that i pass to the procedure as SQL Query.
The values that i have are put in
String_List
and sent to the
procedure
and not
parameters
.
The values if i send as
"+variableName+"
is not accepted.
I have a value in my
String
as
Chicken
for eg.
But i want it to be enclosed in single quote
like this
'Chicken'
.

String variableName;


I know with double quotes we can do like this
"+variableName+"
. This will return in "chicken"

'+variableName+'
does not work.

Answer

To enclose a string in single quotes, you can do this:

String quoted = "'" + food + "'";

Edit:

After seeing your comment about needing it in a SQL query:

You should absolutely NOT pass variables to your SQL-query directly by doing something like this:

String query = "SELECT * FROM FOOD WHERE name = '" + food + "'";

This is vulnerable to SQL-injections!

Instead, you should use prepared statements. Using Spring-JDBC (which I am most familiar with), you can do this:

MapSqlParameterSource params = 
               new MapSqlParameterSource()
                          .addValue("food", food);

String query = "SELECT * FROM FOOD WHERE name = :food";

jdbcTemplate.query(query, params, new FoodRowMapper());

This way, your parameters are prepended with a colon in your query, and then substituted safely with the values in the params-map when you call jdbcTemplate.query.