我這使用FMDB數據庫框架
1.通過路徑創建數據庫
self.db = [FMDatabase databaseWithPath:sqlFilePath];
2.打開數據庫
if ([self.db open]) {
NSLog(@"打開成功");
BOOL success = [self.db executeUpdate:@"CREATE TABLE IF NOT EXISTS t_student (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, age INTEGER DEFAULT 1)"];
if (success) {
NSLog(@"創建表成功");
} else {
NSLog(@"創建表失敗");
}
} else {
NSLog(@"打開失敗");
}
#pragma mark 增加數據
static NSInteger age = 10;
for (int i = 0; i < 20; i++) {
age++;
BOOL success = [self.db executeUpdate:@"INSERT INTO t_student (name, age) VALUES (?, ?);", @"jack", @(age)];
[self.db executeUpdate:@"INSERT INTO t_student (name, age) VALUES(?,?);",@"jack",@(age)];
if (success) {
NSLog(@"插入成功");
} else {
NSLog(@"插入失敗");
}
}
pragma mark 刪除數據
BOOL success = [self.db executeUpdate:@"DELETE FROM t_student WHERE age > 20 AND age < 25;"];
pragma mark 修改數據
BOOL success = [self.db executeUpdate:@"UPDATE t_student SET name = 'liwx' WHERE age > 12 AND age < 15;"];
pragma mark 查詢數據
FMResultSet *result = [self.db executeQuery:@"SELECT id, name, age FROM t_student WHERE age > 25;"];
while ([result next]) {
int ID = [result intForColumnIndex:0];
NSString *name = [result stringForColumnIndex:1];
int age = [result intForColumn:@"age"];
NSLog(@"ID: %zd, name: %@, age: %zd", ID, name, age);
}