FMDB: https://github.com/ccgus/fmdb
按照教程可以通过pods的方式进行依赖引入。
简单的增删改查操作,代码如下:
- #import "ViewController.h"
- #import "FMDB.h"
- @interface ViewController ()
- @property(nonatomic,strong) FMDatabase *db;
- - (IBAction)insert:(UIButton *)sender;
- - (IBAction)delete:(UIButton *)sender;
- - (IBAction)update:(UIButton *)sender;
- - (IBAction)select:(UIButton *)sender;
- @end
- @implementation ViewController
- - (void)viewDidLoad {
- [super viewDidLoad];
- //数据的路径,放在沙盒的cache下面
- NSString *cacheDir = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0];
- NSString *filePath = [cacheDir stringByAppendingPathComponent:@"contact.sqlite"];
- //创建并且打开一个数据库
- _db = [FMDatabase databaseWithPath:filePath];
- BOOL flag = [_db open];
- if (flag) {
- NSLog(@"数据库打开成功");
- }else{
- NSLog(@"数据库打开失败");
- }
- //创建表
- BOOL create = [_db executeUpdate:@"create table if not exists t_health(id integer primary key autoincrement, name text,phone text)"];
- if (create) {
- NSLog(@"创建表成功");
- }else{
- NSLog(@"创建表失败");
- }
- }
- - (IBAction)insert:(UIButton *)sender {
- BOOL insert = [_db executeUpdate:@"insert into t_health (name,phone) values(?,?)",@"jacob",@"138000000000"];
- if (insert) {
- NSLog(@"插入数据成功");
- }else{
- NSLog(@"插入数据失败");
- }
- }
- - (IBAction)delete:(UIButton *)sender {
- BOOL delete = [_db executeUpdate:@"delete from t_health where name like ?",@"jacob"];
- if (delete) {
- NSLog(@"删除数据成功");
- }else{
- NSLog(@"删除数据失败");
- }
- }
- - (IBAction)update:(UIButton *)sender {
- BOOL update = [_db executeUpdate:@"update t_health set name = ? where phone = '%@'",@"jacob111"];
- if (update) {
- NSLog(@"更新数据成功");
- }else{
- NSLog(@"更新数据失败");
- }
- }
- - (IBAction)select:(UIButton *)sender {
- FMResultSet *set = [_db executeQuery:@"select * from t_health "];
- while ([set next]) {
- NSString *name = [set stringForColumn:@"name"];
- NSString *phone = [set stringForColumn:@"phone"];
- NSLog(@"name : %@ phone: %@",name,phone);
- }
- }
- @end