Problems writing strings in sqlite database
I'm fighting with this database and i have a strange problem... If I try to insert as item name a single word, everything works fine, but if the word开发者_如何转开发s are 2 or more, it fails!
This is the portion of the code:
NSString *insertStatementsNS =
[NSString stringWithFormat: @"insert into \"shoppinglist\"
(item, price, groupid, dateadded) values (\"%@\", %@, %d, DATETIME('NOW'))",
name_field, price_field, [groupPicker selectedRowInComponent:0]];
I guess the problem is in the --> \"%@\" <-- but I have no idea in how to fix it.
Can somebody help me?
#
I followed the steps above, but something went wrong, now I have this new error here:
NSString *itemValue = [[NSString alloc] initWithUTF8String: (char*) sqlite3_column_text(dbps, 1)];
and the program stops while starting... It can't read anymore from the DB... what happened?
#
Ok fixed thanks to a friend... we just reset the simulator memory. And we also solve the problem... working in another way.
Instead of using the variable "name_field" I used "itemNameField.text" (directly to the source...) and for some reason it works!
You should avoid directly assigning values to the columns in sql statements. Instead you should use prepared statement
and bind
values to it.
sqlite3_stmt *stmt = nil;
NSString *sqlStr = @"insert into shoppinglist(item, price, groupid, dateadded)
values (?, ?, ?, DATETIME('NOW'))";
char *sql = (char *) [sqlStr UTF8String];
if (sqlite3_prepare_v2(DB, sql, -1, &stmt, NULL) != SQLITE_OK) {
NSAssert1(0, @"Error Preparing Statement: %s", sqlite3_errmsg(DB));
}
sqlite3_bind_text(stmt, 1, name_field, -1, SQLITE_TRANSIENT);
sqlite3_bind_text(stmt, 2, price_field, -1, SQLITE_TRANSIENT);
sqlite3_bind_int(stmt, 3, [groupPicker selectedRowInComponent:0]);
...
Its always safe to use prepared statements, If you directly substitute the string values and if the string values contains special characters like double-quotes("
or "
) then there will be undesired results while executing the sql. But, if you use prepared statements you don't have to worry about the actual contents of the values you bind. Those values will be safely added to the db.
Simply use '%@'
NSString *insertStatementsNS =
[NSString stringWithFormat: @"insert into \"shoppinglist\"
(item, price, groupid, dateadded) values ('%@', %@, %d, DATETIME('NOW'))",
name_field, price_field, [groupPicker selectedRowInComponent:0]];
精彩评论