sTg sTg - 1 year ago 61
Java Question

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

I have a few

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

String variableName;

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

does not work.

Answer Source

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

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


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download