读取本地已经存在的数据库,查询已经放在工程目录下的数据库

来源:互联网 发布:护眼手机膜 知乎 编辑:程序博客网 时间:2024/05/22 10:37

使用sqlite3.0

1.导入sqlite3.0的包

2.在工程里放入.db文件,注意添加的时候要勾选addTarget,否则无法在NSBundlemainBundle中找到。

2.创建个NSObject类,#import<sqlite3.h>

建个方法,方法里写的代码如下:

//获取应用程序的路径

   NSArray *searchPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory ,NSUserDomainMask,YES);

    NSString *doc = [searchPathsobjectAtIndex:0];

   NSString *dbFilePath = [doc stringByAppendingPathComponent:@"superstudent_user.db"];


//获取工程目录下的.db,复制到沙盒里

NSError *error;

    NSBundle *bundle = [NSBundlemainBundle];

    NSString *filenameAgo = [bundlepathForResource:@"superstudent_user"ofType:@"db"];

    NSFileManager *fileManager = [NSFileManager defaultManager];

    [fileManager copyItemAtPath:filenameAgo toPath:dbFilePath error:&error];


//sqlite3打开数据库

sqlite3 *database;

    int databaseResult =sqlite3_open([dbFilePathUTF8String], &database);

    if (databaseResult !=SQLITE_OK) {

        NSLog(@"创建/打开数据库失败,%d",databaseResult);

    }


//查询库

sqlite3_stmt *statement;

    NSMutableArray *arr = [[NSMutableArrayalloc]init];

    if(sqlite3_open([dbFilePathUTF8String],&database)==SQLITE_OK){

       NSString *selectBy =@"SELECT * FROM web_note where   license_type not in('A2B2','DEF','M','A1A3B1NP','A1A3B1','ZABCDJ','ZC','D','ZB','ZA') AND kemu=1";

        constchar *selectBy_C = [selectByUTF8String];


        int searchResult =sqlite3_prepare_v2(database, selectBy_C, -1, &statement,nil);

        if (searchResult !=SQLITE_OK) {

                   NSLog(@"查询失败,%d",searchResult);

                }




0 0