iphone中的登录页面问题

时间:2011-04-06 09:30:49

标签: iphone objective-c sqlite

得到了同样的问题,堆栈溢出之一是:

if(sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK)
{
    //const char *sql ="select Username@'%@',Password@'%@' from userinformation";
    NSString *sql = [[NSString alloc] initWithFormat:@"select * from UserInformation where UserName='%@' and Password='%@' ",Username.text,Password.text];
    sqlite3_stmt *selectSatement;

    // Here i am getting the problem.Im not sure why sqlite3_prepare_v2 ins't meeting SQLITE_OK 
    if( sqlite3_prepare_v2(database, [sql UTF8String], -1, &selectSatement, NULL) == SQLITE_OK)
    {
        //-------------------------------------
        //Loop all the 
        NSString *user1 = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectSatement, 0)];
        NSLog(@"%@",user1);
    }
}

非常感谢任何帮助。

2 个答案:

答案 0 :(得分:0)

检查查询本身,将其打印在日志中并通过从日志中复制并直接在数据库中执行来检查它。

答案 1 :(得分:0)

首先:如果你打开数据库,你也应该使用sqlite3_close(数据库)关闭它

我在下面的代码中写了一个断言语句,它会告诉你,如果你的查询有什么问题。此外,如果您的密码或用户名出于某种原因“nil”,您可能会收到错误,这就是为什么我调整了您设置用户名和密码的方式。如果该值不存在,则为“0”

if(sqlite3_open([dbPath UTF8String], &database) == SQLITE_OK)
{
    char *errorMsg;

    NSString *sql = [[NSString alloc] initWithFormat: @"SELECT * FROM UserInformation WHERE UserName=\"%@\" and Password =\"%@\"", Username.text, Password.text];
    if (sqlite3_exec (database, [sql UTF8String], NULL, NULL, &errorMsg) != SQLITE_OK)
    {
        sqlite3_close(database);
        NSAssert1(0, @"Error selecting data: %s", sqlite3_errmsg(database));
    }
    else
    {
        NSString *user1 = [NSString stringWithUTF8String:((char *)sqlite3_column_text(compiledStatement, 0) ? (char *)sqlite3_column_text(compiledStatement, 0) : (char *)"0")];
        NSString *password1 = [NSString stringWithUTF8String:((char *)sqlite3_column_text(compiledStatement, 1) ? (char *)sqlite3_column_text(compiledStatement, 1) : (char *)"0")];
        NSLog(@"%@: %@",user1,password1);
    }
    [sql release];
}
sqlite3_close(database);

您还应该记住,数据库应该存在于预期的路径中,例如通过调用以下方法

-(void) checkAndCreateDatabase
{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if([fileManager fileExistsAtPath:dbPath]) return;
    NSString *databasePathFromApp = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:databaseName];
    [fileManager copyItemAtPath:databasePathFromApp toPath:databasePath error:nil];
    [fileManager release];
}