下载fmdb,导入头文件FMDB.h
FMDatabase * db;//一般定义属性在Appdelegate里面
获得document路径
NSString * documentPath=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 1, YES)[0];
在document下拼接一个路径(一会生成的文件会直接在document文件夹下)
NSString * dbPath=[documentPath stringByAppendingString:@"/数据库.sqlite"];
初始化(或生成数据库文件)
db=[FMDatabase databaseWithPath:dbPath];
[db open];//如果不用这个方法则不会生成文件
创建表
if ([db open]) {
NSString * createTable=[NSString stringWithFormat:@"CREATE TABLE IF NOT EXISTS USERTABLE (id integer PRIMARY KEY AUTOINCREMENT, name text NOT NULL, age integer NOT NULL);"];
}
插入数据
NSString * insert=[NSString stringWithFormat:@"insert into USERTABLE(name,age) values('%@','%@')",name,age];
if ([db executeUpdate:insert]) {
NSLog(@"插入%@成功",name);
}
删除数据
NSString * delete=[NSString stringWithFormat:@"delete from USERTABLE where name='%@'",name];
if ([db executeUpdate:delete]) {
NSLog(@"删除%@成功",name);
}
修改数据(根据名字修改年龄)
NSString * change=[NSString stringWithFormat:@"UPDATE USERTABLE SET age='%@' where name='%@'",newAge,name];
if ([db executeUpdate:change]) {
NSLog(@"修改 %@ 成功",name);
}
查询数据(根据名字查询年龄)
NSString * select=[NSString stringWithFormat:@"select * from USERTABLE where name='%@'",name];
FMResultSet * set=[db executeQuery:select];
while ([set next]) {
NSString * age=[set stringForColumn:@"age"];
NSLog(@"%@年龄是%@",name,age);
}
遍历数据库
FMResultSet * resultSet=[db executeQuery:@"select * from USERTABLE"];
while ([resultSet next]) {
NSString * name=[resultSet stringForColumn:@"name"];
NSString * age=[resultSet stringForColumn:@"age"];
NSLog(@"%@ 今年 %@岁",name,age);
}