使用FMDatabase操作sqlite3

使用FMDatabase操作sqlite3

使用FMDatabase操作sqlite3数据库非常简单和方便

 //
// main.m
// iOSDemo0602_sqlite3
//
// Created by yao_yu on 14-6-2.
// Copyright (c) 2014年 yao_yu. All rights reserved.
// #import <UIKit/UIKit.h>
#import "FMDatabase.h" void test01();
BOOL isfile(NSString *path);
BOOL isdir(NSString *path); int main(int argc, char * argv[])
{
@autoreleasepool {
test01();
}
return ;
} void test01()
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
NSString *docpath = [paths objectAtIndex:];
NSString *dbpath = [docpath stringByAppendingPathComponent:@"YY/Data2"];
// NSLog(@"%@", dbpath);
if (!isdir(dbpath)) {
NSFileManager *fileManager = [NSFileManager defaultManager];
[fileManager createDirectoryAtPath:dbpath withIntermediateDirectories:YES attributes:nil error:nil];
} NSString *dbfile = [dbpath stringByAppendingPathComponent:@"data.db"];
NSLog(@"%@", dbfile); //初始化
FMDatabase *db = [FMDatabase databaseWithPath:dbfile];
//打开数据库
[db open]; //删除表
[db executeUpdate:@"drop table persons"]; //添加表
[db executeUpdate:@"create table persons(id, name)"]; //删除原有数据
[db executeUpdate:@"delete from persons"]; //使用事务添加数据
[db beginTransaction];
for(int i=; i< ; i++)
{
[db executeUpdate:@"insert into persons values(?,?)", [NSString stringWithFormat:@"%d", i], [NSString stringWithFormat:@"第%d", i]];
}
[db commit]; //数据查询
FMResultSet *cursor = [db executeQuery:@"select * from persons"];
int nCols = cursor.columnCount;
while ([cursor next]) {
for (int i=; i<nCols; i++) {
printf("%s ", [[cursor stringForColumnIndex:i] UTF8String]);
}
printf("\n");
}
cursor = nil; //关闭数据库
[db close]; //删除数据库测试文件
[[NSFileManager defaultManager] removeItemAtPath:dbfile error:nil]; } BOOL isfile(NSString *path)
{
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL isdir = NO;
if ([fileManager fileExistsAtPath:path isDirectory: &isdir]) {
return isdir == NO;
}
return NO;
} BOOL isdir(NSString *path)
{
NSFileManager *fileManager = [NSFileManager defaultManager];
BOOL isdir = NO;
if ([fileManager fileExistsAtPath:path isDirectory: &isdir]) {
return isdir == YES;
}
return NO;
}
04-14 01:24