问题
please anybody tell me how to insert records in sqlite through objective c?
回答1:
You can use a block of code like this
-(NSString*) GetDatabasePath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES) ;
NSString *documentsDirectory = [paths objectAtIndex:0] ;
return [documentsDirectory stringByAppendingPathComponent:@"Your Database"] ;
}
-(void)InsertPurchase {
sqlite3_stmt *statement=nil;
NSString *path = [self GetDatabasePath];
NSString *query;
if(sqlite3_open([path UTF8String],&db) == SQLITE_OK)
{
query = [NSString stringWithFormat: @"Your insert query"];
if(sqlite3_prepare_v2(db, [query UTF8String], -1, &statement, NULL)
== SQLITE_OK)
{
sqlite3_step(statement);
}
sqlite3_finalize(statement);
}
sqlite3_close(db);
}
This can be your interface
@interface Database : NSObject {
sqlite3 *db;
}
回答2:
If you're using FMDB (and honestly if you don't you're crazy), then it's really simple:
FMDatabase* db = [FMDatabase databaseWithPath:@"/path/to/my/database.db"];
if ([db open]) {
[db executeUpdate:@"insert into myTable (col1, col2) values (?, ?)", @"foo", [NSNumber numberWithInt:42]];
[db close];
}
来源:https://stackoverflow.com/questions/4310852/how-to-insert-a-record-in-sqlite