在iOS上使用和访问现有的SQLite数据库 [英] Use and Access Existing SQLite Database on iOS

查看:114
本文介绍了在iOS上使用和访问现有的SQLite数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在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?

推荐答案

使用 FBDB框架可以简化和清理SQLite数据库交互。 FMDB是SQLite C接口的Objective-C包装器。

SQLite database interaction can be made simple and clean by using FBDB Framework. FMDB is an Objective-C wrapper for the SQLite C interface.

参考值得一读:

FMDB Framework文档

带故事板的示例项目

像应用程序包中的任何其他文件一样添加 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


  1. 首先下载 FMDB框架

  2. 现在提取框架从 src / fmdb 文件夹中复制所有文件(不是 src / sample src / extra 文件夹)。

  3. 请点击您的项目位于Xcode的左栏。

  4. 单击中间列中的主要目标。

  5. 单击构建阶段选项卡。

  6. 展开使用库链接二进制文件旁边的箭头。

  7. 单击+ 按钮。

  8. 搜索libsqlite3.0.dylib并双击它。

  1. First download the FMDB framework
  2. Extract the framework now copy all the file from src/fmdb folder (not the src/sample or src/extra folders).
  3. Click your project in the left column of Xcode.
  4. Click the main target in the middle column.
  5. Click the "Build Phases" tab.
  6. Expand the arrow next to "Link Binary With Libraries".
  7. Click the "+" button.
  8. 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];   
}



插入查询



Insert Query

#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];
}



更新查询



Update Query

- (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];
}



删除查询



Delete Query

#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:

#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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆