2012-03-06 78 views
1
- (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; 
} 

下面是我的日誌輸出:sqlite的,選擇查詢不起作用

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我的數據庫是確定:

我找不到問題?

+0

讓我看看你的數據庫路徑 – Hector 2012-03-06 10:38:17

回答

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; 
+0

非常感謝你,用你的方法,我找到了問題! – Tan 2012-03-06 12:37:51

0

刪除sqlString末尾的''和'Use Semicolon'中的引號。

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

嘗試此當要轉換的SqlString爲char

常量字符*的SqlCommand =(字符*)[的SqlString cStringUsingEncoding:NSUTF8StringEncoding];