2

I have to insert certain text in database which may contain characters with single quotes and double quotes.

For eg: "Lumix" or something like Vijay's

I have successfully escaped the double quotes like this:

if(fdata.search('"') != -1) {


fdata = fdata.replace(/(['"])/g, "\\$1");



}  

But I am not understanding how to escape the single quotes. Without escaping the single quotes SQLite is not accepting the data. How to solve the issue? Thanks in advance!

kittu88
  • 2,451
  • 5
  • 40
  • 80

3 Answers3

4

Use parameters, then you don't need to escape anything:

db.execute('INSERT INTO MyTable(ID, Name) VALUES(?, ?)', 123, name);
CL.
  • 173,858
  • 17
  • 217
  • 259
  • what about the update query? db.execute("UPDATE formData SET form_xml_id=" + findex + ",dateTime_stamp='" + datetime + "',data='" + "" + "',user_id=" + Ti.App.information.user_id + ",status='"+ DataStatus +"' where unique_id='" + Ti.App.mydata._guid + "'"); – kittu88 Feb 25 '13 at 12:09
  • 2
    Same principle: `db.execute("UPDATE formData SET form_xml_id=?, dateTime_stamp=?, data=?, user_id=?, status=?, where unique_id=?", findex, datetime, '', Ti.App.information.user_id, DataStatus, Ti.App.mydata._guid);` :-) – Martijn Feb 25 '13 at 12:14
  • 1
    See the documentation here: http://docs.appcelerator.com/titanium/latest/#!/api/Titanium.Database.DB-method-execute – Martijn Feb 25 '13 at 12:17
1

CL.'s answer is the by far best solution, but if you want to make this work without rewriting your code you could add this function:

function removeQuotes(str){
return str.replace(/'/g, "'").replace(/"/g,""");
}

Usage:

fdata = removeQuotes(fdata);

That worked for me

RobertH
  • 355
  • 7
  • 17
0

Use replaceAll method for replacing '(single quote) with space as below:

     String name= name.replaceAll("'", "''");
Avadhani Y
  • 7,566
  • 19
  • 63
  • 90