第三方:FMDateBase ,需导入libsqlite3.tbd
另一个常用数据库:realm
创建表
NSString *path = @"/Users/apple/Desktop/dataBase.sqlite";
_dataBase = [FMDatabase databaseWithPath:path];
//如果要操作dataBase必须先要打开
if (![_dataBase open]) {
[_dataBase open];
}
//创建表
[_dataBase executeUpdate:@"create table if not exists 'Person' (Name text,Age integer)"];
//用完关闭
[_dataBase close];
插入数据
- 完整SQL插入
NSString *insertSQL = @"INSERT INTO Student (name, age,address) VALUES ('张三', 23, '长沙')";
if ([database executeUpdate:insertSQL]) {
NSLog(@"insert OK");
}
else {
NSLog(@"Insert Error: %@", database.lastErrorMessage);
}
- 使用占位符SQL插入
NSString *insertSQL = @"INSERT INTO Student (name, age, address) VALUES (?, ?, ?)";
//后面的参数使用与C语言中类型对应的Objective-C对象
if ([database executeUpdate:insertSQL, @"李四", @19, @"长沙"]) {
NSLog(@"insert OK");
}
else {
NSLog(@"Insert Error: %@", database.lastErrorMessage);
}
NSString *insertSQL = @"INSERT INTO Student (name, age, address) VALUES (%@, %@, %@)";
if ([database executeUpdateWithFormat:insertSQL, @"张三", @20, @"长沙"]) {
%@ NSLog(@"Insert Error: %@", database.lastErrorMessage);
NSLog(@"insert OK");
}
else {
NSLog(@"Insert Error: %@", database.lastErrorMessage);
}
- 带字典的占位符SQL插入
NSString *insertSQL = @"INSERT INTO Student (name, age, address) VALUES (:name, :age, :address)";
NSDictionary *dict = @{@"name":@"张三", @"age":@18, @"address":@"长沙"};
if ([database executeUpdate:insertSQL withParameterDictionary:dict]) {
NSLog(@"insert OK");
} else {
NSLog(@"Insert Error: %@", database.lastErrorMessage);
}
FMDB查询数据
NSString *querySQL = @"SELECT * FROM Student";
//1. 执行查询操作
FMResultSet *rs = [database executeQuery:querySQL];
//2. 获取一条记录, 成功还回YES
while ([rs next]) {
//3. 通过字段名获取数据
NSInteger stuId = [rs longForColumn:@"stuId"];
//4. 通过字段位置获取数据
NSString *name = [rs stringForColumnIndex:1];
int age = [rs intForColumnIndex:2];
NSString *address = [rs stringForColumn:@"address"];
NSLog(@"%ld:%@:%d:%@", stuId, name, age, address);
}
NSString *querySQL = @"SELECT * FROM Student";
[database executeStatements:querySQLwithResultBlock:^int(NSDictionary *resultsDictionary) {
//多次调用, 每次用字典返回一条记录
NSLog(@"%@", resultsDictionary);
return 0;
}];
FMDB多线程
- 多线程队列
databaseQueueWithPath:path];[queue inDatabase:^(FMDatabase *db) {
[db executeUpdate:@"INSERT INTO Student (name, age,address) VALUES ('张三', 29, '长沙')"];
[db executeUpdate:@"INSERT INTO Student (name, age,address) VALUES ('李四', 27, '娄底')"];
[db executeUpdate:@"INSERT INTO Student (name, age,address) VALUES ('王五', 24, '常德')"];}];
- 支持事务操作
[queue inTransaction:^(FMDatabase *db, BOOL *rollback) {
[db executeUpdate:@"INSERT INTO Student (name, age, address)VALUES (' ', 29, ' ')"];
[db executeUpdate:@"INSERT INTO Student (name, age, address)VALUES (' ', 27, ' ')"];
// 回滚
// if (某种条件) {
// *rollback = YES;
// return;
// }
[db executeUpdate:@"INSERT INTO Student (name, age, address)VALUES (' ', 24, ' ')"];
}];