0

我正在开发一个使用 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 不允许我添加新的,

请在下面找到我的更新;

这是代码的更新版本:

视图加载部分;

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

buraya başka birşey yaz

- (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");
}

正如我上面指出的,错误是 Error=no such table: peopleto and stmt is returned null

4

2 回答 2

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]);
    }
}
于 2013-05-10T04:34:50.737 回答
0

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

于 2013-05-10T11:34:49.987 回答