从sqldatabase表c#中获取公共id号

本文关键字:id 获取 sqldatabase | 更新日期: 2023-09-27 18:09:12

我需要知道如何获得所有#2的客户端ID,这样我就可以获得分配给它们的程序…到目前为止,我的代码只获得了第一个包含#2的客户端标识…

int progs;
string Command = @"select * from clientprogram where clientProgClientID = @clientID;";
using (MySqlConnection mConnection = new MySqlConnection(mycon))
{
     mConnection.Open();
     using (MySqlCommand cmd2 = new MySqlCommand(Command, mConnection))
     {
          cmd2.Parameters.Add(new MySqlParameter("@clientID", lblcID.Text));
          using (MySqlDataReader reader = cmd2.ExecuteReader())
          {
                if (reader.Read())
                {
                     progs = (int)reader["clientProgramID"];
                     cmbProgram.Items.Add(progs);
                }
          }
     }
     mConnection.Close();
}

从sqldatabase表c#中获取公共id号

更改

if (reader.Read())

while (reader.Read())

似乎应该循环递归地添加记录,而不仅仅是第一个

当然,它只得到第一个结果,因为您只读取了一次。使用while(reader.Read())而不是if(reader.Read())

while(reader.Read())
{
      progs = (int)reader["clientProgramID"];
      cmbProgram.Items.Add(progs);
}                           

更改

if (reader.Read())

while(reader.Read())

旁注;当您只需要单列数据时,不要使用select *,使用select Coumnname from yourtable

int progs;
string Command = @"select * from clientprogram where clientProgClientID =     @clientID;";
using (MySqlConnection mConnection = new MySqlConnection(mycon))
{
 mConnection.Open();
 using (MySqlCommand cmd2 = new MySqlCommand(Command, mConnection))
  {
      cmd2.Parameters.Add(new MySqlParameter("@clientID", lblcID.Text));
      using (MySqlDataReader reader = cmd2.ExecuteReader())
      {
            while (reader.Read()) // CHANGE TO THIS
            {
                 progs = (int)reader["clientProgramID"];
                 cmbProgram.Items.Add(progs);
            }
      }
 }
 mConnection.Close();

}