This week's book giveaway is in the OCAJP forum.
We're giving away four copies of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) and have Khalid A Mughal & Rolf W Rasmussen on-line!
See this thread for details.
Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Escape characters in JDBC (single quote/apostrophe)

 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My java code works fine as long as the field does not contain a single quote. Since the strings are wrapped in single quotes when sent to the DBMS, strings containing single quotes mess up the statement.
I have created a pseudo example, removing much of the code, leaving only what I think is important for this question:
------------
String name_var = "O'Maley";
query_smt = "insert name_table(the_name) values('" + name_var + "'";
try
{
ResultSet rset = m_statement.executeQuery(query_smt);
}
catch(java.lang.Exception e)
{
....
}
------------
Please, any help on how I can pass the string with the single quote to the DBMS would be greatly appriciated.
(I am using Sybase)
MP
 
Bhupinder Dhillon
Ranch Hand
Posts: 124
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Escape the single quote with another single quote:
String name_var = "O''Maley";

query_smt = "insert name_table(the_name) values('" + name_var + "'";
The above will insert "O'Maley".
[This message has been edited by Bhupinder Dhillon (edited March 08, 2001).]
[This message has been edited by Bhupinder Dhillon (edited March 08, 2001).]
 
Anthony Cunningham
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
or use prepared statement, it seems not to have a problem with '
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic