sqlite,选择查询不起作用

时间:2012-03-06 10:04:41

标签: iphone sqlite

- (UserInfo*)getCurrentUserInfo:(NSString*)userName
{
    UserInfo *userInfo = [[UserInfo alloc]init];

    sqlite3 *database;
    sqlite3_stmt *selectstmt;
    NSLog(@"userName:%@",userName);
    if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
        NSString *sqlString = [NSString stringWithFormat:@"SELECT USER_LEVEL FROM USER_INFO WHERE USER_NAME = '%@'" , userName];
        NSLog(@"getCurrentUserInfo:%@",sqlString);
        const char *SqlCommand = [sqlString UTF8String];
        if (sqlite3_prepare_v2(database, SqlCommand, -1, &selectstmt, NULL) == SQLITE_OK) {
            NSLog(@"success!");
            while (sqlite3_step(selectstmt) == SQLITE_ROW) {
                NSString *userInfoStr = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 0)];
                NSLog(@"select result:%@",userInfoStr);
            }
        }
        sqlite3_finalize(selectstmt);
    }
    sqlite3_close (database);
    return userInfo;
}

以下是我的日志输出:

2012-03-06 17:50:11.556 MagicWords[508:f803] userName:Tan
2012-03-06 17:50:11.557 MagicWords[508:f803] getCurrentUserInfo:SELECT USER_LEVEL FROM USER_INFO WHERE USER_NAME = 'Tan'

它不会打印“成功”,所以sqlite3_prepare_v2不会返回yes.but我的数据库没问题:

我找不到问题?

3 个答案:

答案 0 :(得分:2)

添加sqlite错误消息。它将深入了解内部情况。如果您的数据库的所有内容都正确,请检查表名。

UserInfo *userInfo = [[UserInfo alloc]init];

    sqlite3 *database;
    sqlite3_stmt *selectstmt;
    NSLog(@"userName:%@",userName);
    if(sqlite3_open([databasePath UTF8String], &database) == SQLITE_OK) {
        NSString *sqlString = [NSString stringWithFormat:@"SELECT USER_LEVEL FROM USER_INFO WHERE USER_NAME = '%@'" , userName];
        NSLog(@"getCurrentUserInfo:%@",sqlString);
        const char *SqlCommand = [sqlString UTF8String];
        if (sqlite3_prepare_v2(database, SqlCommand, -1, &selectstmt, NULL) == SQLITE_OK) {
            NSLog(@"success!");
            while (sqlite3_step(selectstmt) == SQLITE_ROW) {
                NSString *userInfoStr = [NSString stringWithUTF8String:(char *)sqlite3_column_text(selectstmt, 0)];
                NSLog(@"select result:%@",userInfoStr);
            }
        }
      //Add the error message here.
       else
        {

         NSLog(@"%s",sqlite3_errmsg(database));

        }
       ///////
        sqlite3_finalize(selectstmt);
    }
    sqlite3_close (database);
    return userInfo;

答案 1 :(得分:0)

删除''中的引号,并在sqlString的末尾使用Semicolon。

NSString *sqlString = [NSString stringWithFormat:@"SELECT USER_LEVEL FROM USER_INFO WHERE USER_NAME = %@;" , userName];

答案 2 :(得分:0)

在将sqlString转换为char

时尝试此操作
  

const char * SqlCommand =(char *)[sqlString   cStringUsingEncoding:NSUTF8StringEncoding];