记录一个基础的IOS下SQLite的例子:
@implementation ViewController - (void)viewDidLoad { [super viewDidLoad]; NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *filename = @"test-db"; NSString *dictionary = [paths objectAtIndex:0]; NSString *dbPaths = [dictionary stringByAppendingPathComponent:filename]; int result = sqlite3_open([dbPaths UTF8String], &_db); char *errMsg; const char *sql_create_stmt = "CREATE TABLE t_user(username varchar(50), password varchar(50));"; if(result == SQLITE_OK){ if (sqlite3_exec(_db, sql_create_stmt, NULL, NULL, &errMsg) != SQLITE_OK) { NSLog(@"Failed to create table: %s", errMsg); return; } }else{ NSLog(@"Failed to open database"); return; } const char *sql_insert_stmt1 = "INSERT INTO t_user(username, password) VALUES('fredric','123')"; const char *sql_insert_stmt2 = "INSERT INTO t_user(username, password) VALUES('sinny','123')"; if(sqlite3_exec(_db, sql_insert_stmt1, NULL, NULL, &errMsg) != SQLITE_OK){ NSLog(@"Failed to insert table"); } if(sqlite3_exec(_db, sql_insert_stmt2, NULL, NULL, &errMsg) != SQLITE_OK){ NSLog(@"Failed to insert table"); } const char *sql_select_stmt = "SELECT * FROM t_user"; sqlite3_stmt *stemt = NULL; sqlite3_prepare_v2(_db, sql_select_stmt, -1, &stemt, NULL); // 判断有没有查询结果 while (sqlite3_step(stemt) == SQLITE_ROW) { // 取出第一个字段的查询得结果 const unsigned char *username = sqlite3_column_text(stemt, 0); const unsigned char *password = sqlite3_column_text(stemt, 1); NSLog(@"%s %s", username, password); } } - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Dispose of any resources that can be recreated. } @end
执行结果:
2016-04-16 11:12:19.693 ios20[1628:89155] fredric 123
2016-04-16 11:12:19.694 ios20[1628:89155] sinny 123