基础
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory = [paths objectAtIndex:0];
NSString *dbPath = [documentDirectory stringByAppendingPathComponents:@"student.db"];
FMDatabase *db = [FMDatabase databaseWithPath:dbPath];
if(![db open]) {
return;
}
新建表
[db executeUpdate:@"CREATE TABLE PersonList (Name text, Age integer, Sex integer, Phone text, Address text, Photo blob)];
插入数据
[db executeUpdate:@"INSERT INTO PersonList(Name, Age, Sex, Phone, Address, Photo) VALUES(?,?,?,?,?,?)",
@"Xemtof",[NSNumber numberWithInt:20],@0,@"1888888888",@"Shanghai",[NSData dataWithContentsOfFile:filePath]
];
在SQLite中数据对应的关系如下
SQlite | OC |
---|---|
text | NSString |
integer | NSNumber |
blob | NSDate |
获取数据
FMResultSet *rs = [db executeQuery@"SELECT Name, Age FROM PersonList"];
while([rs next])
{
NSString *name = [rs stringForColumn:@"Name"];
int age = [rs intForColumn:@"Age"];
}
[rs close];
快速获取数据
NSString *address = [db stringForQuery:@"SELECT Address FROM PersonList WHERE Name=?", @"xemtof"];
int age = [db intForQuery:@"SELECT Age FROM PersonList WHERE Name=?", @"xemtof"];