sqlite3_prepare_v2()== SQLITE_OK返回NO,找不到现有表

时间:2013-05-10 04:18:51

标签: iphone sqlite

我正在开发一个使用sqlite3数据库文件的iphone应用程序。我正在使用以下代码从sqlite3数据库中选择;

NSString* dbYolu = [NSString stringWithFormat:@"%@/emhdb3.sqlite3",NSHomeDirectory()];

sqlite3* db;

NSLog(@"%@ dbyolu : ", dbYolu);

if (sqlite3_open([dbYolu UTF8String], &db) == SQLITE_OK)
{
    NSString *query = [NSString stringWithFormat: @"SELECT username, mobile FROM peopleto WHERE namesurname=\"%@\"", name.text];
    NSLog(@"%@ : query", query);
    sqlite3_stmt *stmt;

    if (sqlite3_prepare_v2(db, [query UTF8String], -1, &stmt, nil) == SQLITE_OK) //  statement stmt returns null and returns SQLITE_OK = FALSE.
    {
        NSLog(@"stepped in SQLITE_OK is TRUE");
        while (sqlite3_step(stmt) == SQLITE_ROW)
        {
            NSString* ders_kodu = [NSString stringWithUTF8String:(char*)sqlite3_column_text(stmt, 0)];
            double not = sqlite3_column_double(stmt, 1);

            NSLog(@"%@ : %f", ders_kodu, not);
        }
    }
    else
    {
        NSLog(@"%@ - but failed", stmt);
    }
    sqlite3_finalize(stmt);
}
else
    NSLog(@"db could not be opened");

它在“sqlite3_prepare_v2(db,[query UTF8String],-1,& stmt,nil)== SQLITE_OK”点上面失败了。并且错误是:“错误:没有这样的表:peopleto。但是当我在sql浏览器中运行此查询时,它成功返回表的内容。我的意思是这个查询是正确的并且有效。

顺便说一下,我在viewLoad

上获得了带有以下代码的路径名文件
- (void)viewDidLoad
{
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: @"emhdb3.sqlite3"]];

NSLog(@"dbpath : %@", databasePath);
NSFileManager *filemgr = [NSFileManager defaultManager];

if ([filemgr fileExistsAtPath: databasePath ] == NO)
{
    const char *dbpath = [databasePath UTF8String];
    NSLog(@"db not found");
    if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
    {
        NSLog(@"SQLITE_OK is passed");
        //.... some codes here, doesn't metter for me because SQLITE_OK = true
    } else {
        status.text = @"Failed to open/create database";
    }
}
else if ([filemgr fileExistsAtPath:databasePath] == YES)
{
    NSLog(@"i found the file here : %s",[databasePath UTF8String]);
}
NSLog(@"completed");
[super viewDidLoad];
}

我在项目文件夹中有数据库文件并添加到项目中。 我错过了什么?

谢谢

///////

我很抱歉更新了我的问题,但stackoverflow不允许我添加新的,

请在下面找到我的更新;

以下是代码的更新版本:

viewLoad part;

- (void)viewDidLoad
{
[self createEditableCopyOfDatabaseIfNeeded];

NSString *docsDir;
NSArray *dirPaths;
dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
docsDir = [dirPaths objectAtIndex:0];
databasePath = [[NSString alloc] initWithString:[docsDir stringByAppendingPathComponent:@"emhdb3.sqlite3"]];

NSLog(@"dbpath : %@", databasePath);
NSFileManager *filemgr = [NSFileManager defaultManager];

if ([filemgr fileExistsAtPath: databasePath ] == NO)
{
const char *dbpath = [databasePath UTF8String];
    if (sqlite3_open(dbpath, &contactDB) == SQLITE_OK)
    {
        char *errMsg;
        const char *sql_stmt = "CREATE TABLE IF NOT EXISTS peopleto (pId INTEGER PRIMARY KEY AUTOINCREMENT, namesurname TEXT, mobile TEXT)";
        if (sqlite3_exec(contactDB, sql_stmt, NULL, NULL, &errMsg) != SQLITE_OK)
        {
            status.text = @"Failed to create table";
        }
        sqlite3_close(contactDB);
    } else {
        status.text = @"Failed to open/create database";
    }
}
else if ([filemgr fileExistsAtPath:databasePath] == YES)
{
    NSLog(@"%s is filepath",[databasePath UTF8String]);
}
NSLog(@"checkpoint 4");
[super viewDidLoad];
}

burayabaşkabirşeyyaz

- (void)createEditableCopyOfDatabaseIfNeeded {
NSLog(@"entered createEditableCopyOfDatabaseIfNeeded");
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"emhdb3.sqlite3"];
success = [fileManager fileExistsAtPath:writableDBPath];
if (success)
{
    NSLog(@"success == YES returned");
    return;
}
NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"emhdb3.sqlite3"];
success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
if (!success) {
    NSLog( @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
}
else{
    NSLog(@"checkpoint 2");
}
}

并执行选择查询的部分;

-(IBAction)findcontact2:(id)sender
{
NSString *dbYolu = databasePath;
sqlite3* db;

NSLog(@"%@ dbyolu : ", dbYolu);

if (sqlite3_open([dbYolu UTF8String], &db) == SQLITE_OK)
{
    NSString *query = [NSString stringWithFormat: @"SELECT namesurname, mobile FROM peopleto"]; //any query

    NSLog(@"%@ : query", query);

    sqlite3_stmt *stmt;

    if (sqlite3_prepare_v2(db, [query UTF8String], -1, &stmt, nil) == SQLITE_OK)
    {
        NSLog(@"SQLITE is OK");
        while (sqlite3_step(stmt) == SQLITE_ROW)
        {
            NSString* ders_kodu = [NSString stringWithUTF8String:(char*)sqlite3_column_text(stmt, 0)];
            double not = sqlite3_column_double(stmt, 1);

            NSLog(@"%@ : %f", namesurname, mobile);
        }
    }
    else
    {
        NSLog(@"Error=%s",sqlite3_errmsg(db));   // error message : Error=no such table: peopleto
        NSLog(@"%@ - is stmt", stmt); //stmt is null
    }
    sqlite3_finalize(stmt);
}
else
    NSLog(@"could not open the db");
}

正如我上面所指出的,错误是错误=没有这样的表:peopleto和stmt返回null

2 个答案:

答案 0 :(得分:1)

您是否将SQL文件复制到文档中,如果不是,则需要先将其复制到文档中。将SQL文件添加到项目时,它将添加到您的包中,而不是添加到文档目录中。你需要复制第一个

- (void)createEditableCopyOfDatabaseIfNeeded {
    // First, test for existence.
    BOOL success;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSError *error;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *writableDBPath = [documentsDirectory stringByAppendingPathComponent:@"bookdb.sql"];
    success = [fileManager fileExistsAtPath:writableDBPath];
    if (success)
        return;
    // The writable database does not exist, so copy the default to the appropriate location.
    NSString *defaultDBPath = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"bookdb.sql"];
    success = [fileManager copyItemAtPath:defaultDBPath toPath:writableDBPath error:&error];
    if (!success) {
        NSLog( @"Failed to create writable database file with message '%@'.", [error localizedDescription]);
    }
}

答案 1 :(得分:0)

请检查主捆绑包中的数据库是否包含该表,然后尝试将其复制到资源文件夹并应用上述