-3

总是无法打开数据库。
我正在尝试插入数据。数据被完美插入。
但是当我当时调用获取数据的方法(选择查询)时,数据库无法打开。
我从来没有关闭过数据库。
每次都必须关闭数据库吗?

if(sqlite3_open([self.databasePath UTF8String], &database) == SQLITE_OK)

提前致谢

4

1 回答 1

2

没有看到完整的代码,我们怎么能指出你的编码错误?...所以我猜你没有将你的数据库复制到文档目录。所以这里是示例代码,根据你的要求使用它。快乐编码:-)

-(void) viewdidload
{

    NSString *databaseName=@"xxx.sqlite";

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

    NSString *docsDir=[documentPaths objectAtIndex:0];

    databasePath=[docsDir stringByAppendingPathComponent:databaseName];

    [self checkAndCreateDatabase];//Copy db to documents directory
    [self readFromDB];
}

-(void)checkAndCreateDatabase
{

     BOOL success;

// Create a FileManager object, we will use this to check the status
// of the database and to copy it over if required
NSFileManager *fileManager = [NSFileManager defaultManager];

// Check if the database has already been created in the users filesystem
success = [fileManager fileExistsAtPath:databasePath];

// If the database already exists then return without doing anything
if(success) return;

// If not then proceed to copy the database from the application to the users filesystem

// Get the path to the database in the application package
NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];

// Copy the database from the package to the users filesystem
[fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];


}


-(void)readFromDB

{

sqlite3 *database;

if(sqlite3_open([databasePath UTF8String], &database)==SQLITE_OK)
{

    NSString *querySql=[NSString stringWithFormat:@"Select * from xxx"];

    const char *sqlStatement=[querySql UTF8String];

    sqlite3_stmt *compiledStatement;

    if(sqlite3_prepare_v2(database, sqlStatement, -1, &compiledStatement, NULL) == SQLITE_OK) {
        // Loop through the results and add them to the feeds array

        while(sqlite3_step(compiledStatement) == SQLITE_ROW)  {
           //get the data from db here                


        }

        sqlite3_finalize(compiledStatement);
    }

    sqlite3_close(database);
}

}
于 2013-01-23T05:09:08.280 回答