本文用一個完整範例走過 iOS 上 SQLite 的原生操作:開啟資料庫、建表、插入、查詢。程式碼可直接貼進 ViewController 跑起來。
#import <sqlite3.h>
@interface ViewController () {
sqlite3 *_sqldb;
}
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self OpenDb];
[self createTable];
[self insertData];
[self FindData];
}
// 開啟資料庫
- (void)OpenDb {
NSArray *arrs = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
// 資料庫不存在就建立,存在就直接開啟
NSString *path = [arrs lastObject];
NSString *documentpath = [path stringByAppendingPathComponent:@"sql.db"];
int reslut = sqlite3_open([documentpath UTF8String], &_sqldb);
if (reslut == SQLITE_OK) {
NSLog(@"數據庫已被打開");
}
}
// 透過資料庫實例建表
- (void)createTable {
// 不帶參數的 SQL
const char *sql = "create table if not exists t_person (id integer primary key autoincrement, name text, age integer);";
char *error;
// sqlite3_exec 可以執行任何不帶參數的 SQL;帶參數時不建議使用,以免 SQL 注入
int resutl = sqlite3_exec(_sqldb, sql, NULL, NULL, &error);
if (resutl == SQLITE_OK) {
NSLog(@"創建表成功");
} else {
NSLog(@"創建表失敗--》%s", error);
}
}
// 插入資料
- (void)insertData {
// "?" 是帶參數的佔位符
const char *sql = "insert into t_person(name, age) values(?, ?);";
sqlite3_stmt *stmp;
// 執行前先檢查語法,-1 代表讓 SQLite 自行計算字串長度
int result = sqlite3_prepare_v2(_sqldb, sql, -1, &stmp, NULL);
if (result == SQLITE_OK) {
NSLog(@"插入 SQL 語句語法沒有問題");
// 綁定參數,索引從 1 開始
sqlite3_bind_text(stmp, 1, "gcb", -1, NULL);
sqlite3_bind_int(stmp, 2, 12);
// 執行帶參數的 SQL(不能用 exec)
int stepResult = sqlite3_step(stmp);
// 插入結果要用 SQLITE_DONE 判斷
if (stepResult == SQLITE_DONE) {
NSLog(@"插入成功");
} else {
NSLog(@"插入失敗");
}
} else {
NSLog(@"插入 SQL 語句有問題");
}
}
// 查詢資料
- (void)FindData {
char *sql = "select id, name, age from t_person";
sqlite3_stmt *stmt;
// 先檢查語法
int result = sqlite3_prepare_v2(_sqldb, sql, -1, &stmt, NULL);
if (result == SQLITE_OK) {
while (sqlite3_step(stmt) == SQLITE_ROW) {
// 注意:查詢欄位索引從 0 開始,綁定參數則從 1 開始
int xh = sqlite3_column_int(stmt, 0);
char *name = (char *)sqlite3_column_text(stmt, 1);
int age = sqlite3_column_int(stmt, 2);
NSLog(@"xh=%i-->name=%s-->age=%i", xh, name, age);
}
} else {
NSLog(@"查詢 SQL 語法有誤");
}
}
@end
幾個容易忽略的重點:帶參數的 SQL 一律走 prepare + bind + step,不要圖省事用 exec 拼字串;每次 prepare 都要有一個對應的 sqlite3_finalize;查詢時 sqlite3_step 回傳 SQLITE_ROW 代表有資料、SQLITE_DONE 代表結束,兩者用途不同別搞混。