gpt4 book ai didi

c# - 获取满足sql查询的第二条记录

转载 作者:行者123 更新时间:2023-11-30 17:44:17 26 4
gpt4 key购买 nike

我试图用数据库中的任务名称填充我的列表框,其中优先级等于我的 List<object> 中的项目。 .

下面的代码填充列表框,但错误是在我的数据库中我有两条优先级为 1 的记录,因此它只找到第一条记录并输出两次。为了修复之前显示两条记录两次的错误,我添加了 break;现在只显示满足 sql 查询的第一条记录。

我这样做是因为用户可以选择按优先级排序,所以我获取所有优先级值并将它们存储在 List<object> 中,通过冒泡排序实现对它们进行排序,然后执行下面的代码以用户想要的顺序将它们输出回列表框。

所以我的问题是,如何正确输出数据库中的所有记录?

for (int i = 0; i < list.Count; i++)
{
string sql = "SELECT [Task Name] FROM Tasks WHERE Priority = " + Convert.ToInt32(list[i].GetValue(0));
using (OleDbCommand cmd = new OleDbCommand(sql, conn))
{
using (OleDbDataReader dataReader = cmd.ExecuteReader())
{
List<object[]> taskNameList = new List<object[]>();

if (dataReader.HasRows) //if the table isnt empty
{
while (dataReader.Read()) //loop to the end of the database
{
object[] tasks = new object[dataReader.FieldCount]; //object array of same length as the amount of task names in database
taskNameList.Add(tasks);
for (int j = 0; j <= dataReader.FieldCount - 1; j++)
{
tasks[j] = dataReader[j]; //fill object array with task names
}
taskList.Items.AddRange(tasks); //add to list box
break;
}
}
}
}
}

最佳答案

我通过在 while 循环中放置一个 if 语句来解决这个问题,以在我将它添加到列表框之前测试列表框是否已经包含任务名称。下面的代码如下:

  while (dataReader.Read()) //loop to the end of the database
{
if (taskList.Items.Contains(dataReader[0]) == false) //so that it doesn't duplicate records in the list box that satisfy the priority value
{
object[] tasks = new object[dataReader.FieldCount]; //object array of same length as the amount of task names in database
taskNameList.Add(tasks);
for (int j = 0; j <= dataReader.FieldCount - 1; j++)
{
tasks[j] = dataReader[j]; //fill object array with task names
}
taskList.Items.AddRange(tasks); //add to list box

}
}

关于c# - 获取满足sql查询的第二条记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29859487/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com