我这使用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);
}
网友评论