How to insert a record in Sqlite?
please 开发者_StackOverflow中文版anybody tell me how to insert records in sqlite through objective c?
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;
}
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];
}
精彩评论