如何将数据从sqlite提取到数组中

时间:2014-10-31 09:43:28

标签: ios objective-c sqlite

这是我的代码。 它只返回数据库的第一行。我知道有些事情是错的,但不知道是什么。请帮忙。

if(sqlite3_open([databasePath UTF8String],&texttalkdb)==SQLITE_OK)
{
    sqlite3_stmt *statement;

    if(sqlite3_prepare_v2(texttalkdb, [sql UTF8String], -1,&statement, NULL)==SQLITE_OK)
    {
        if(sqlite3_step(statement)==SQLITE_ROW)
        {
            for(int i=0;i<=20;i++)
        {
            char *pass=(char*)sqlite3_column_text(statement,i);
            NSString *passStr = [NSString stringWithFormat:@"%s",pass];

                NSString *msg=[[NSString alloc]initWithUTF8String:pass];
                [arr addObject:msg];
          }
        }
        sqlite3_finalize(statement);
    }
    sqlite3_close(texttalkdb);
}
NSLog(@"%@",arr);
return arr;

2 个答案:

答案 0 :(得分:2)

试试这个

if(sqlite3_prepare_v2(texttalkdb, [sql UTF8String], -1,&statement, NULL)==SQLITE_OK)
{
            while( sqlite3_step(statement) == SQLITE_ROW )
            {
            //get records   
        }
}

答案 1 :(得分:0)

第1步:这是为了检查获取值是否为空

 +(NSString*)charToString:(char*)chart
 {
    NSString *string = @" ";
    if(string)
    {
      chart = [self checkEmptyChar:chart];
      string=[NSString stringWithUTF8String:chart];
    }
   return string;
 }

第2步:这是用于检查字符

+(char *)checkEmptyChar:(char *)check
{
  NSString *string = @" ";
  if (check == NULL)
    check = string;
  return check;
}

第3步:要获取SQLite编码

 if (sqlite3_prepare_v2(database, [query UTF8String], -1, &stment, nil) == SQLITE_OK)

    {
        while (sqlite3_step(stment) == SQLITE_ROW)

        {

            for(int i=0;i<=20;i++)

            {
                 NSString *msg = [self charToString: (char *)sqlite3_column_text(stment, i)];

                 [array addObject:msg];
            } 

        }

        sqlite3_reset(stment);
    }

    sqlite3_finalize(stment);
 }

sqlite3_close(database);