问题
I have an insert statement for my sqlite table that contains apostrophes in the values.
NSString *sqlInsert = [NSString stringWithFormat:@"insert into myTable (_id, name, area, title, description, url) VALUES (%i, '%@', '%@', '%@', '%@', '%@')", tempObject.ID, tempObject.name, tempObject.area, tempObject.title, tempObject.description, tempObject.url];
The results of that string is this
insert into myTable (_id, name, area, title, description, url) VALUES (0, 'John Smith', 'USA', 'Programmer', 'John Smith is a programmer. He programs a lot. John Smith's duty is to program. He loves it. His dog's name is Billy.', 'www.google.com')
When I try to insert that into the table, I get a syntax error near "s". I want to properly escape the apostrophes. How would I go about doing that? Thanks, any insight is appreciated!
Edit: We have solved our issue. We had entered some single quotes (') into our strings where we really wanted curly single quotes. The curly single quotes do not mess with the SQLite insert statements. For those who have this problem, you could possibly use single curly quotes instead of regular single quotes. This may not be possible in your circumstances, but for some it could be a simple solution.
回答1:
The issue is your data contains single quote in it. You have two option to overcome this.
- Escape
'
with\'
- Use sqlite3_bind_xxx() method for binding the values ( I prefer this method). You can do it like:
NSString *sqlInsert = @"insert into myTable (_id, name, area, title, description, url) VALUES (?, ?, ?, ?, ?, ?)";
if (sqlite3_open([yourDBPath UTF8String], &yourDB) == SQLITE_OK)
{
if (sqlite3_prepare_v2(yourDB, sql, 1, &stmt, NULL) == SQLITE_OK)
{
sqlite3_bind_int(stmt, 1, tempObject.ID);
sqlite3_bind_text(stmt, 2, [tempObject.name UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(stmt, 3, [tempObject.area UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(stmt, 4, [tempObject.title UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(stmt, 5, [tempObject.description UTF8String], -1, SQLITE_TRANSIENT);
sqlite3_bind_text(stmt, 6, [tempObject.url UTF8String], -1, SQLITE_TRANSIENT);
// Execute
}
}
来源:https://stackoverflow.com/questions/27761453/how-to-properly-escape-single-quotes-in-sqlite-insert-statement-ios