2

我创建了我的表并使用firefox sqlite manager扩展插入了我的数据,保存并添加了我的sqlitefile,它是“notifications.sqlite”,之后我写了这段代码,但它什么也没输出。

打开 .sqlite 文件和 .db 文件有什么区别吗?如何正确打开我的数据库?

*更新: *调试后,朋友评论它在这一行有问题:

databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: @"notifications.sqlite"]];

  if ([filemgr fileExistsAtPath: databasePath ] == YES)

if 不是 YES 所以它会丢失一切所以 databasePath 有点错误

我的表如下:

CREATE TABLE "quotes_type" ("type_id" INTEGER PRIMARY KEY  AUTOINCREMENT  NOT NULL , "content" VARCHAR)

这是我打开 .sqlite 文件的努力:

- (void)viewDidLoad{

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

    NSString *docsDir = [dirPaths objectAtIndex:0];
    databasePath = [[NSString alloc] initWithString: [docsDir stringByAppendingPathComponent: @"notifications.sqlite"]];
    sqlite3_stmt *statement;
    NSFileManager *filemgr = [NSFileManager defaultManager];
    if ([filemgr fileExistsAtPath: databasePath ] == YES)
    {
    if (sqlite3_open([databasePath UTF8String], &contactDB) == SQLITE_OK)
    {

        NSString *qrycount = [NSString stringWithFormat: @"select * from quotes_type"];

        const char *count_stmt = [qrycount UTF8String];

        sqlite3_prepare_v2(contactDB, count_stmt, -1, &statement, NULL);
        if (sqlite3_step(statement) == SQLITE_ERROR) {
            NSAssert1(0,@"Error when selecting rows  %s",sqlite3_errmsg(contactDB));
        } else {
              NSLog(@"negin");
            int myid=sqlite3_column_int(statement, 0);
            NSString *text = [NSString stringWithUTF8String:(char *)sqlite3_column_text(statement,1)];
            NSLog(@"myid is %d",myid);
            NSLog(@"text is %@",text);
            sqlite3_finalize(statement);
            sqlite3_close(contactDB);
        }
    }
    else NSLog(@"openning has problem");
    }
}
4

2 回答 2

1

您正在检查Documents. 但是你曾经在那里复制过吗?如果没有,你永远不会在那里找到它。您确实想检查该文件,如果找不到,请将其从捆绑包复制到Documents文件夹中。因此,如果在 中找不到数据库Documents,则应通过以下方式复制它:

NSError *error;
NSString *bundleDatabasePath = [[NSBundle mainBundle] pathForResource:@"notifications" ofType:@"sqlite"];
NSAssert(bundleDatabasePath, @"database not found in bundle");
if (![filemgr copyItemAtPath:bundleDatabasePath toPath:databasePath error:&error])
    NSLog(@"%s: copyItemAtPath failure: error = %@", __FUNCTION__, error); 
于 2013-04-07T15:21:42.167 回答
0

您可以使用 FMDB 来管理您的 sqlite 数据库,这非常简单。

github:FMDB

于 2013-04-08T04:01:24.883 回答