I'm trying to do an insert statement with SQLite and I'm sure I must be doing something stupid, but I can't figure out how to get it to work.
The error I'm getting is: "Error preparing statement"
Here's my code:
NSString *json_string = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];
// Create new SBJSON parser object
SBJsonParser *parser = [[SBJsonParser alloc] init];
// parse the JSON response into an object
NSDictionary *download = [parser objectWithString:json_string error:nil];
NSDictionary *buildings =开发者_如何学Go [download objectForKey:@"buildings"];
// Open DB
sqlite3 *db = [RLSampleAppDelegate getNewDBConnection];
// Buildings
for (NSDictionary *building in buildings)
{
NSDictionary *thisbuilding = [building objectForKey:@"building"];
NSLog(@"%@", [thisbuilding objectForKey:@"buildingname"]);
sqlite3_stmt *statement = nil;
NSString* someString = [NSString stringWithFormat:@"INSERT INTO building (buildingid, buildingname) VALUES (\'%@\', \'%@\')", [thisbuilding objectForKey:@"buildingid"], [thisbuilding objectForKey:@"buildingname"]];
NSLog(@"somestring: %@", someString);
const char *sql = (const char *) someString;
if(sqlite3_prepare_v2(db, sql, -1, &statement, NULL)!=SQLITE_OK)
NSAssert1(0,@"Error preparing statement",sqlite3_errmsg(db));
while(sqlite3_step(statement) == SQLITE_DONE){}
sqlite3_finalize(statement);
}
[json_string release];
You can't use a NSString
instance in the SQLite3
API. You need a pure C string.
So, try changing this:
const char *sql = (const char *) someString;
Into:
const char *sql = [someString cStringUsingEncoding:[NSString defaultCStringEncoding]];
Try this:
sqlite3_prepare_v2(db, [someString UTF8String], -1, &statement, nil)
First you need sure that you get database file from Document or Library folder of simulator. Because you can not insert databases stored in the app resources. And try my code.
NSString *json_string = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
[responseData release];
// Create new SBJSON parser object
SBJsonParser *parser = [[SBJsonParser alloc] init];
// parse the JSON response into an object
NSDictionary *download = [parser objectWithString:json_string error:nil];
NSDictionary *buildings = [download objectForKey:@"buildings"];
// Open DB
sqlite3 *db = [RLSampleAppDelegate getNewDBConnection];
// Buildings
for (NSDictionary *building in buildings)
{
NSDictionary *thisbuilding = [building objectForKey:@"building"];
NSLog(@"%@", [thisbuilding objectForKey:@"buildingname"]);
NSString* someString = [NSString stringWithFormat:@"INSERT INTO building (buildingid, buildingname) VALUES ('%@','%@')", [thisbuilding objectForKey:@"buildingid"], [thisbuilding objectForKey:@"buildingname"]];
const char *sql = [someString UTF8String];
char *error;
if (sqlite3_exec(db, sql, NULL, NULL, &error)==SQLITE_OK) {
NSLog(@"insert success.");
}
}
[json_string release];
精彩评论