下載fmdb,導(dǎo)入頭文件FMDB.h
FMDatabase? * db;//一般定義屬性在Appdelegate里面
獲得document路徑
NSString * documentPath=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, 1, YES)[0];
在document下拼接一個(gè)路徑(一會(huì)生成的文件會(huì)直接在document文件夾下)
NSString * dbPath=[documentPath stringByAppendingString:@"/數(shù)據(jù)庫.sqlite"];
初始化(或生成數(shù)據(jù)庫文件)
db=[FMDatabase databaseWithPath:dbPath];
[db open];//如果不用這個(gè)方法則不會(huì)生成文件
創(chuàng)建表
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);"];
}
插入數(shù)據(jù)
NSString * insert=[NSString stringWithFormat:@"insert into USERTABLE(name,age) values('%@','%@')",name,age];
if ([db executeUpdate:insert]) {
NSLog(@"插入%@成功",name);
}
刪除數(shù)據(jù)
NSString * delete=[NSString stringWithFormat:@"delete from USERTABLE where name='%@'",name];
if ([db executeUpdate:delete]) {
NSLog(@"刪除%@成功",name);
}
修改數(shù)據(jù)(根據(jù)名字修改年齡)
NSString * change=[NSString stringWithFormat:@"UPDATE USERTABLE SET age='%@' where name='%@'",newAge,name];
if ([db executeUpdate:change]) {
NSLog(@"修改 %@ 成功",name);
}
查詢數(shù)據(jù)(根據(jù)名字查詢年齡)
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);
}
遍歷數(shù)據(jù)庫
FMResultSet * resultSet=[db executeQuery:@"select * from USERTABLE"];
while ([resultSet next]) {
NSString * name=[resultSet stringForColumn:@"name"];
NSString * age=[resultSet stringForColumn:@"age"];
NSLog(@"%@ 今年 %@歲",name,age);
}