0

我在连接到我的 sqlite 数据库时遇到了一些问题。我使用的是 xcode 版本 4.4.1

这是我的代码..

NSString *docsDir;
NSArray *dirPaths;

// Get the documents directory
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

docsDir = [dirPaths objectAtIndex:0];

// Build the path to the database file
databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: @"signature.db"]];

NSFileManager *filemgr = [NSFileManager defaultManager];

if ([filemgr fileExistsAtPath: databasePath ] == NO)
{
    const char *dbpath = [databasePath UTF8String];

    if (sqlite3_open(dbpath, &database) == SQLITE_OK)
    {
        status.text = @"Connected..";

    } else {
        status.text = @"Failed to open/create database..";
    }
}

[filemgr release];

有什么建议..?

谢谢,

繁荣

4

2 回答 2

0

如果您的应用程序包中有一个预构建的数据库文件,您可能希望检查数据库文件是否到位,以便您可以将其放入您的文档文件夹中。当然,当您增强应用程序时,任何架构更改都需要在代码中完成。这是我使用的一些代码(有效,但需要稍微更新)

打开/创建数据库时,我使用它来指定数据库文件的位置。我没有将它与 init 放在一起,因为我的位置在 iOS 和 Mac OS X 之间是不同的,我希望 DB 代码同时与两者一起使用:

NSString *dbFilePath;
NSArray *searchPaths = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentFolderPath = searchPaths[0];
dbFilePath = [documentFolderPath stringByAppendingPathComponent: @"MyDBFile.db"];
MyDB* appDB = [[EasySpendLogDB alloc] initWithFile:dbFilePath];
if(!appDB) {
    // show error
    return;
}

这是在我的数据库访问类中。它使用了我写的一些包装类:

- (id) initWithFile: (NSString*) filePathName {
if(!(self = [super init])) return nil;

BOOL myPathIsDir;
BOOL fileExists = [[NSFileManager defaultManager]
                         fileExistsAtPath: filePathName
                         isDirectory: &myPathIsDir];
NSString *backupDbPath = [[NSBundle mainBundle]
                                  pathForResource:@"MyDBFile"
                                  ofType:@"db"];

if (backupDbPath != nil && !fileExists) {
    [[NSFileManager defaultManager]
                            copyItemAtPath:backupDbPath
                            toPath:filePathName
                            error:nil];
}

db = [[ABSQLiteDB alloc] init];
if(![db connect:filePathName]) {
    return nil;
}

[self checkSchema]; // this is where schema updates are done (see project sample)

return self;
}

您可能还想查看我编写的这个包含示例项目的 Objective-c 包装器:https ://github.com/AaronBratcher/ABSQLite

于 2013-07-23T13:12:55.223 回答
0

无需检查数据库是否存在;sqlite3_open_v2()参考)将创建数据库,如果它不存在,如果你传递标志SQLITE_OPEN_CREATE

NSString *dbPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPath:@"signature.db"];

if (sqlite3_open_v2([dbPath UTF8String], &database, SQLITE_OPEN_READWRITE|SQLITE_OPEN_CREATE) == SQLITE_OK)
{
    status.text = @"Connected..";
    // Check the schema and install if it doesn't exist
    sqlite3_close(database);
} else {
    status.text = @"Failed to open/create database..";
}
于 2013-01-11T16:14:51.520 回答