说起数据库便想起4个字,增删改查。
今天学习的下FMDB 数据库管理框架。
个人认为他的中心思想很简单,只需要关心sql语句,所以核心方法只有一种,执行sql语句。
两个主要类FMDatabase,FMResultSet。
两种主要方法,executeUpdate,executeQuery。
执行sql语句分为2种,一种是需要返回值,一种是不需要返回值。
其中无返回值的包括 增,删,改,(executeUpdate)有返回值的是 查(executeQuery)。这些都是FMDatabase的方法,查询的时候要返回数据有时是多条,所以分装了另一个类FMResultSet。
FMDB 用起来很简单 下边测试方法,一看便知。
-(void)test
{
NSString * bundlepath = [[NSBundle mainBundle] pathForResource:@"Test" ofType:@"sqlite"];
NSString * documentStr = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *realPath = [documentStr stringByAppendingPathComponent:@"Test.sqlite"];
NSLog(@"%@",documentStr);
if (![[NSFileManager defaultManager] fileExistsAtPath:realPath]) {
[[NSFileManager defaultManager] copyItemAtPath:bundlepath toPath:realPath error:nil];
}
FMDatabase * database = [FMDatabase databaseWithPath:realPath];
if (![database open]) {
NSLog(@"can't open");
}
else
{
[database executeUpdate:@"create table if not exists people(name TEXT,age INT)"];
[database executeUpdate:@"insert into people (name,age) values(?,?)",@"susan",@1];
[database executeUpdate:@"insert into people (name,age) values(?,?)",@"lina",@2];
NSString * selectResult = [database stringForQuery:@"select name from people where age = ?",@1];
NSLog(@"%@",selectResult);
FMResultSet * resultSet = [database executeQuery:@"select * from people"];
int j = 1;
while ([resultSet next]) {//循环行
NSLog(@"地%d条数据",j);
NSLog(@"%@---%d",[resultSet stringForColumn:@"name"],[resultSet intForColumn:@"age"]);
for (int i = 0; i<[resultSet columnCount]; i++) {//循环列
NSLog(@"%@",[resultSet stringForColumnIndex:i]);
}
j++;
}
}
}
对比下系统的 会发现简单的多
-(void)test2
{
NSString * bundlepath = [[NSBundle mainBundle] pathForResource:@"Test" ofType:@"sqlite"];
NSString * documentStr = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *realPath = [documentStr stringByAppendingPathComponent:@"Test.sqlite"];
NSLog(@"%@",documentStr);
if (![[NSFileManager defaultManager] fileExistsAtPath:realPath]) {
[[NSFileManager defaultManager] copyItemAtPath:bundlepath toPath:realPath error:nil];
}
sqlite3 * db =NULL;
if (sqlite3_open([realPath UTF8String], &db)!= SQLITE_OK)
{
NSLog(@"can't open");
}
else
{
sqlite3_stmt * stmt = NULL;
char * sql = (char*)[@"create table if not exists city(name TEXT,age INT)" UTF8String];
int result = 0;
result = sqlite3_prepare_v2(db, sql , -1, &stmt, NULL);
result=sqlite3_step(stmt);
sqlite3_finalize(stmt);
stmt = NULL;
sql = "insert into city (name,age) values(?,?)";
result = sqlite3_prepare_v2(db, sql , -1, &stmt, NULL);
result = sqlite3_bind_text(stmt, 1, "pk", -1, NULL);
result = sqlite3_bind_int(stmt, 2, 10);
result =sqlite3_step(stmt);
sqlite3_finalize(stmt);
sql = "select * from city";
sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
while (sqlite3_step(stmt)==SQLITE_ROW)
{
NSLog(@"%s",sqlite3_column_text(stmt, 0));
NSLog(@"%d",sqlite3_column_int(stmt, 1));
}
sqlite3_finalize(stmt);
}
}