在 iOS 上使用和访问现有的 SQLite 数据库 [英] Use and Access Existing SQLite Database on iOS
问题描述
我在 SQLite 中有一个完全填充的数据库,我想在我的新应用程序中使用它.它相当大,所以如果可能的话,我想避免将其更改为另一种格式.我怎样才能以我的应用附带的方式使用这个数据库?
I have a fully populated database in SQLite that I'd like to use in my new app. It's rather large, so I'd like to avoid changing it to another format if possible. How can I use this database in such a way that it ships with my app?
例如,如果我只是将文件放入支持的文件目录中,我该如何访问它?我如何引用它?
If I just drop the file into my Supported Files directory, for example, how can I access it? How do I reference it?
推荐答案
使用 FMDB Framework
可以使 SQLite 数据库交互变得简单和干净.FMDB 是 SQLite C 接口的 Objective-C 包装器.
SQLite database interaction can be made simple and clean by using FMDB Framework
. FMDB is an Objective-C wrapper for the SQLite C interface.
值得一读的参考:
像应用程序包中的任何其他文件一样添加SQLite DB
,然后使用以下代码将数据库复制到文档目录,然后使用文档目录中的数据库>
Add the SQLite DB
like any other file in your application's bundle then copy the database to documents directory using the following code then use the database from the documents directory
- 首先下载FMDB框架
- 现在提取框架从
src/fmdb
文件夹(不是src/sample
或src/extra
文件夹)复制所有文件. - 在 Xcode 的左栏中单击您的项目.
- 点击中间栏中的主要目标.
- 点击构建阶段"标签.
- 展开将二进制文件与库链接"旁边的箭头.
- 点击+"按钮.
- 搜索 libsqlite3.0.dylib 并双击它.
- First download the FMDB framework
- Extract the framework now copy all the file from
src/fmdb
folder (not thesrc/sample
orsrc/extra
folders). - Click your project in the left column of Xcode.
- Click the main target in the middle column.
- Click the "Build Phases" tab.
- Expand the arrow next to "Link Binary With Libraries".
- Click the "+" button.
- Search for libsqlite3.0.dylib and double click it.
将您的现有数据库
复制到didFinishLaunchingWithOptions:
中的应用程序文档
中,并在整个应用程序中维护数据库路径.
Copying your existing database
into app's document
in didFinishLaunchingWithOptions:
and maintain the database path through out the application.
在您的 AppDelegate 中添加以下代码.
In your AppDelegate add the following code.
AppDelegate.m
#import "AppDelegate.h"
@implementation AppDelegate
// Application Start
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Function called to create a copy of the database if needed.
[self createCopyOfDatabaseIfNeeded];
return YES;
}
#pragma mark - Defined Functions
// Function to Create a writable copy of the bundled default database in the application Documents directory.
- (void)createCopyOfDatabaseIfNeeded {
// First, test for existence.
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
// Database filename can have extension db/sqlite.
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *appDBPath = [documentsDirectory stringByAppendingPathComponent:@"database-name.sqlite"];
success = [fileManager fileExistsAtPath:appDBPath];
if (success) {
return;
}
// The writable database does not exist, so copy the default to the appropriate location.
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"database-name.sqlite"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:appDBPath error:&error];
NSAssert(success, @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
}
YourViewController.m
#import "FMDatabase.h"
- (void)getAllData {
// Getting the database path.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsPath = [paths objectAtIndex:0];
NSString *dbPath = [docsPath stringByAppendingPathComponent:@"database-name.sqlite"];
FMDatabase *database = [FMDatabase databaseWithPath:dbPath];
[database open];
NSString *sqlSelectQuery = @"SELECT * FROM tablename";
// Query result
FMResultSet *resultsWithNameLocation = [database executeQuery:sqlSelectQuery];
while([resultsWithNameLocation next]) {
NSString *strID = [NSString stringWithFormat:@"%d",[resultsWithNameLocation intForColumn:@"ID"]];
NSString *strName = [NSString stringWithFormat:@"%@",[resultsWithNameLocation stringForColumn:@"Name"]];
NSString *strLoc = [NSString stringWithFormat:@"%@",[resultsWithNameLocation stringForColumn:@"Location"]];
// loading your data into the array, dictionaries.
NSLog(@"ID = %d, Name = %@, Location = %@",strID, strName, strLoc);
}
[database close];
}
插入查询
#import "FMDatabase.h"
- (void)insertData {
// Getting the database path.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsPath = [paths objectAtIndex:0];
NSString *dbPath = [docsPath stringByAppendingPathComponent:@"database-name.sqlite"];
FMDatabase *database = [FMDatabase databaseWithPath:dbPath];
[database open];
NSString *insertQuery = [NSString stringWithFormat:@"INSERT INTO user VALUES ('%@', %d)", @"Jobin Kurian", 25];
[database executeUpdate:insertQuery];
[database close];
}
更新查询
- (void)updateDate {
// Getting the database path.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsPath = [paths objectAtIndex:0];
NSString *dbPath = [docsPath stringByAppendingPathComponent:@"fmdb-sample.sqlite"];
FMDatabase *database = [FMDatabase databaseWithPath:dbPath];
[database open];
NSString *insertQuery = [NSString stringWithFormat:@"UPDATE users SET age = '%@' WHERE username = '%@'", @"23", @"colin" ];
[database executeUpdate:insertQuery];
[database close];
}
删除查询
#import "FMDatabase.h"
- (void)deleteData {
// Getting the database path.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsPath = [paths objectAtIndex:0];
NSString *dbPath = [docsPath stringByAppendingPathComponent:@"database-name.sqlite"];
FMDatabase *database = [FMDatabase databaseWithPath:dbPath];
[database open];
NSString *deleteQuery = @"DELETE FROM user WHERE age = 25";
[database executeUpdate:deleteQuery];
[database close];
}
附加功能
获取行数
确保包含 FMDatabaseAdditions.h
文件以使用 intForQuery:
.
Make sure to include the FMDatabaseAdditions.h
file to use intForQuery:
.
#import "FMDatabase.h"
#import "FMDatabaseAdditions.h"
- (void)gettingRowCount {
// Getting the database path.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsPath = [paths objectAtIndex:0];
NSString *dbPath = [docsPath stringByAppendingPathComponent:@"database-name.sqlite"];
FMDatabase *database = [FMDatabase databaseWithPath:dbPath];
[database open];
NSUInteger count = [database intForQuery:@"SELECT COUNT(field_name) FROM table_name"];
[database close];
}
这篇关于在 iOS 上使用和访问现有的 SQLite 数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!