How to write the query for retrieving id from sqlite database table in iphone apps

余生长醉 提交于 2020-01-25 10:32:06

问题


I am new to using the SQLite database in iphone apps. I have created a database with login table in it and added the database to the project. Login table contains 3 fields ID, Username and Password fields. I am entering the username and password in the textfields of the view. Now I am looking of how to retrieve the id from the login table when username and password entered are correct by checking the table. Can anyone help out in this.

My Code:

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

回答1:


You need to have your SQL statement in a format usable by sqlite3. You might do something like this:

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

Since sqlite is a C library you will need to get the UTF8 version of the select string and pass that to the sqlite lib:

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



回答2:


I got it working by writing the code like this:

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

Its working good for me now.



来源:https://stackoverflow.com/questions/2381555/how-to-write-the-query-for-retrieving-id-from-sqlite-database-table-in-iphone-ap

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!