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

这篇博客介绍了如何在iOS应用中使用SQLite3.0来读取本地已存在的数据库文件。首先,需要将.db文件添加到工程并设置属性为addTarget。然后,创建一个NSObject子类,导入sqlite3.h头文件。通过获取文档目录路径,将工程目录下的数据库文件复制到沙盒中。接着,打开数据库并执行查询语句,筛选出特定条件的数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用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);

                }




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值