Reputation: 569
I'm having a list object and im sending to SQL query as
UPDATE <table name> SET status= 'CLOSED' WHERE dlno IN ("+StringUtils.join(deals, ',')+") ";
My deals object is as follows
1549886508071HELMPFN
How can I pass a string here
[SQL0103] Numeric constant 1549886508071HELMPFN not valid.
Upvotes: 0
Views: 1506
Reputation: 687
Using bind variables will solve your quote problem and make your code safe against SQL injection:
List<String> deals = ImmutableList.of("abc", "123", "def");
StringBuilder questionMarks = new StringBuilder("?");
for (int i=1;i<deals.size();i++) {
questionMarks.append(",?");
}
Connection conn = ...; // presumably, you already have this
PreparedStatement stmt = conn.prepareStatement(
"UPDATE my_table SET status= 'CLOSED' WHERE dlno IN (" + questionMarks + ")");
for (int i=1;i<=deals.size();i++) { // note these are 1-indexed, not 0-indexed
stmt.setString(i, deals.get(i-1));
}
stmt.executeUpdate();
Basically, you'll generate a query that says UPDATE my_table SET status = 'CLOSED' WHERE dlno IN (?,?)
(the number of question marks corresponding to the number of parameters), and then you'll update them with stmt.setString
. And then you can execute your update.
Also note you'll need to deal with SQLException
s and closing the statement. Removed here for clarity.
Upvotes: 1
Reputation: 1269953
String constants need to be enclosed in single quotes. In your case this would look like:
UPDATE <table name>
SET status = 'CLOSED'
WHERE dlno IN ('"+StringUtils.join(deals, "', '") +"') ";
Upvotes: 1