C# SQL DataReader:如何只读一次
本文关键字:SQL 一次 只读 何只读 DataReader | 更新日期: 2023-09-27 18:32:03
只有一次,谢谢你的帮助!
Public string panda(string lola = @"Server=.'SQLEXPRESS; DataBase=panda; Integrated Security=true;")
{
SqlConnection panda = new SqlConnection(lola);
panda.Open();
return lola;
}
public string Show_details(string Command = "Select name From panda")
{
SqlConnection cn = new SqlConnection(panda());
SqlCommand Show;
SqlDataReader read;
Show = new SqlCommand(Command, cn);
cn.Open();
read = Show.ExecuteReader();
while (read.Read())
{
listBox1.Items.Add(read["name"]);
}
return Command;
}
private void button3_Click(object sender, EventArgs e)
{
Show_details();
}
我正在寻找如何让读者读取数据并将其仅发布一次到列表框中!
如果我正确理解了你的问题,你只想进入阅读器循环一次。 "虽然",没有双关语,有更有效的方法可以解决这个问题,你可以声明一个布尔标志,看看你是否已经进入循环。进入循环后,将其更改为 false,以便在下次评估 while 条件时,它将计算为 false 结束循环。见下文。
public string Show_details(string Command = "Select name From panda")
{
SqlConnection cn = new SqlConnection(panda());
SqlCommand Show;
SqlDataReader read;
Show = new SqlCommand(Command, cn);
cn.Open();
read = Show.ExecuteReader();
// Declare flag to see if you've hit the reader yet.
bool hasntYetRead = true;
// Add a second condition to determine if to cursor through again
while (read.Read() && hasntYetRead )
{
listBox1.Items.Add(read["name"]);
// Change the flag to false
hasntYetRead = false;
}
return Command;
}
如果您希望将来能够更改次数或迭代次数,则可以使用计数器。
public string Show_details(string Command = "Select name From panda")
{
SqlConnection cn = new SqlConnection(panda());
SqlCommand Show;
SqlDataReader read;
Show = new SqlCommand(Command, cn);
cn.Open();
read = Show.ExecuteReader();
// declare counter
int counter = 0;
// Add a second condition to determine if to cursor through again
while (read.Read() && counter < 1) //could get counter to count to user input number
{
listBox1.Items.Add(read["name"]);
// Change the flag to false
counter++;
}
return Command;
}