【问题标题】:C# SQL DataReader : How to Read only One timeC# SQL DataReader:如何只读一次
【发布时间】:2016-01-26 18:03:52
【问题描述】:

只有一次,谢谢你的帮助!

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();
}

我正在寻找如何让阅读器读取数据并将其仅在列表框中发布一次!

【问题讨论】:

  • 使用DataTableSqlDataAdapter
  • 或者至少,在 Show_details() 方法的开头清除列表框。更好的办法是传入您要显示的列表框,这样您就可以在方法中使用该参数,而不是将其直接绑定到特定的列表框。

标签: c# sql sql-server datareader


【解决方案1】:

如果我正确理解了您的问题,您只想进入阅读器循环一次。 '虽然',没有双关语的意思,有更有效的方法来解决这个问题,你可以声明一个 bool 标志来查看你是否已经进入循环。一旦进入循环,将其更改为 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;
}

【讨论】:

  • 我试图通过将 start 的值更改为另一个值来使用 MySettings 做同样的事情,但感谢它的完美!
  • 如果你只想得到一个第一行,为什么不在 SELECT 查询中只到 TOP 1?
【解决方案2】:

如果您希望将来能够更改次数或迭代次数,可以使用计数器。

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;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-23
    相关资源
    最近更新 更多