我在我的应用程序中使用 sqlite 数据库。在我的 sqlite 中存在 10 条记录。我想从这个数据库中读取 4 个数据,我想获取这些数据,直到最后一个数据中的 BroID 为 NULL(BroID 是列数据之一)这是我的代码,但我不知道如何在我的代码中使用循环,直到 BroID 成为空值。
-(NSMutableArray *)readInformationFromDatabase
{
array = [[NSMutableArray alloc] init];
// Setup the database object
sqlite3 *database;
// Open the database from the users filessytem
if(sqlite3_open([[self dataFilePath] UTF8String], &database) == SQLITE_OK)
{
// I want to use loop for certain work!!! (this work is get name from data base until BroID to be NULL )
NSString *sqlStatement_userInfo =[NSString stringWithFormat:@"Select * from table1"];
sqlite3_stmt *compiledStatement;
if(sqlite3_prepare_v2(database, [sqlStatement_userInfo UTF8String], -1, &compiledStatement, NULL) == SQLITE_OK)
{
// Loop through the results and add them to the feeds array
while(sqlite3_step(compiledStatement) == SQLITE_ROW)
{
// Init the Data Dictionary
NSMutableDictionary *_dataDictionary=[[NSMutableDictionary alloc] init];
NSString *_userName = [NSString stringWithUTF8String:(char *)sqlite3_column_text(compiledStatement, 1)];
[_dataDictionary setObject:[NSString stringWithFormat:@"%@",_userName] forKey:@"Name"];
[array addObject:_dataDictionary];
}
}
else
{
NSLog(@"No Data Found");
}
请告诉我完成此代码的想法。
最佳答案
首先确定 SELECT
语句:
- 将语句从
SELECT * ...
更改为SELECT colname1, colname2, ...
这样您就可以确定返回列的顺序,并且您不必引用模式来找出它们返回的顺序。这实际上节省了时间。 BroID
必须包含在所选列中。- 您需要一个
ORDER BY
子句以获得一致的结果。 - 您可以让数据库只包含
WHERE BroID IS NOT NULL
行,这可能会满足您的需求。
如果您仍然需要使用代码来停止抓取,那么只需测试 NULL BroID
列并从 while
中break
循环使用:
while (sqlite3_step(compiledStatement) == SQLITE_ROW)
{
// Fetch other columns
if (sqlite_column_type(compiledStatement, INDEX) == SQLITE_NULL)
break;
}
其中 INDEX
是 BroID
的列索引。
不清楚是否要在结果集中包含BroID IS NULL
的行;如果您不执行 sqlite_column_type()
测试 before 获取列,否则保持如上。
引用reference了解详情。
关于ios - 如何在sqlite中使用循环从特定列获取名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16621281/