如何在iphone应用程序中编写用于从sqlite数据库表中检索id的查询

时间:2010-03-04 17:59:26

标签: iphone sqlite

我是在iphone应用程序中使用SQLite数据库的新手。我创建了一个包含登录表的数据库,并将数据库添加到项目中。登录表包含3个字段IDUsernamePassword字段。我在视图的文本字段中输入用户名和密码。现在我正在研究如何通过检查表格输入的用户名和密码是正确的,从登录表中检索id。任何人都可以帮忙解决这个问题。

我的代码:

-(void)checkInDatabase
{
    if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK)
    {
        //uid = "select count(*) from logins where Username==txtusername.text and Password==txtpassword.text";
        NSString* sql =[[NSString alloc] initWithFormat:@"select id from login where Username =%s and Password=%s;",txtusername.text,txtpassword.text];

        [sql UTF8String];
        sqlite3_stmt *statement;
        if(sqlite3_prepare_v2(database, sql, -1, &statement, NULL) == SQLITE_OK)
        {
            if(sqlite3_step(statement) == SQLITE_ROW);
            {
                uid =[NSString stringWithUTF8String:(char*)sqlite3_column_text(statement, 1)]; 
            }
        }
        else
        {
            uid =0;
        }
        sqlite3_finalize(statement);
    }
    sqlite3_close(database);
}

2 个答案:

答案 0 :(得分:1)

您需要以sqlite3可用的格式提供SQL语句。你可能会这样做:

NSString *select = [[NSString alloc] initWithFormat:@"select id from login where Username=%s and Password=%s;", txtusername.text, txtpassword.text];

由于sqlite是一个C库,你需要获取select字符串的UTF8版本并将其传递给sqlite lib:

if (sqlite3_prepare_v2(database, [sql UTF8String], -1, &statement, NULL) == SQLITE_OK)

答案 1 :(得分:0)

我通过编写如下代码来实现它:

NSString* sql = [[NSString alloc] initWithFormat:
                                  @"select id from login where Username='%@' and  
                                  Password='%@'",txtusername.text,txtpassword.text];

现在它对我有用。

相关问题