標籤:
SQLite3.0使用的是C的函數介面,常用函數如下:
sqlite3_open() //開啟資料庫
sqlite3_close() //關閉資料庫
sqlite3_exec() //執行sql語句,例如建立表
sqlite3_prepare_v2() //編譯SQL語句
sqlite3_step() //執行查詢SQL語句
sqlite3_finalize() //結束sql語句
sqlite3_bind_text() //綁定參數
sqlite3_column_text() //查詢欄位上的資料
建立資料庫表
sqlite3 *sqlite = nil;
NSString *filePath = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/%@",@"data.sqlite"];
int result = sqlite3_open([filePath UTF8String],&sqlite);
if (result = SQLITE_OK) {
NSLog(@"開啟資料失敗");
}
//建立表的SQL語句
NSString *sql = @"CREATE TABLE UserTable (userId text NOT NULL PRIMARY KEY UNIQUE,username text, age integer)";
char *error;
//執行SQL語句
result = sqlite3_exec(sqlite,[sql UTF8String],NULL, NULL, &error);
if (result != SQLITE_OK) {
NSLog(@"建立資料庫失敗,%s",erorr);
}
sqlite_close(sqlite);
插入資料
sqlite3 *sqlite = nil;
sqlite3_stmt = *stmt = nil;
NSString *filePath = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/%@",@"data.sqlite"];
int result = sqlite3_open([filePath UTF8String],&sqlite);
if (result = SQLITE_OK) {
NSLog(@"開啟資料失敗");
}
NSString *sql = @"INSERT INTO UserTable(userId,userName,age) VALUES(?,?,?)";
sqlite3_prepare_v2(sqlite, [sql UTF8String], -1, &stmt ,NULL);
NSString *userId = @"1002";
NSString *username = @"張三";
int age = 3;
//往SQL中填充資料
sqlite3_bind_text(stmt, 1, [userId UTF8String], -1 NULL);
sqite3_bind_text(stmt, 2, [userName UTF8String], -1,NULL);
sqite3_bind_int(stmt, 3, age);
result = sqlite3_step(stmt);
if (result == SQLITE_ERORR || result == SQLITE_MISUSE) {
NSLog(@"執行SQL語句失敗");
return NO;
}
sqlite3_finalize(stmt);
sqlite3_close(sqlite);
查詢資料
sqlite3 *sqlite = nil;
sqlite3_stmt = *stmt = nil;
NSString *filePath = [NSHomeDirectory() stringByAppendingFormat:@"/Documents/%@",@"data.sqlite"];
int result = sqlite3_open([filePath UTF8String],&sqlite);
if (result = SQLITE_OK) {
NSLog(@"開啟資料失敗");
}
NSString *sql = @"SELECT userId, userName,age FROM UserTable WHERE age >?";
sqlite3_prepare_v2(sqlite, [sql UTF8String], -1,&stmt, NULL);
int age = 1;
sqlie3_bind_int(stmt, 1,age);
result = sqlite3_step(stmt);
//迴圈遍曆查詢後的資料列表
while (result == SQLITE_ROW) {
char *userid = (char*)sqlite3_column_text(stmt,0);
char *username = (char*)sqlite3_column_text(stmt,1);
int age = sqlite3_column_int(stmt,2);
NSString *userId = [NSString stringWithCString:userid encoding:NSUTF8StringEncoding];
NSString *userName = [NSString stringWithCString:username encoding:NSUTF8StringEncoding];
NSLog(@"-----使用者名稱:%@,使用者id:%@,年齡:%d---",userName,userId,age);
result = sqlite3_step(stmt);
}
sqlite3_finalize(stmt);
sqlite3_close(sqlite);
SQLite常用函數及語句