从sqldatabase表c获取公共id号

时间:2015-08-23 03:44:08

标签: c# mysql visual-studio-2013

我需要知道如何获取所有#ID的clientID,这样我才能获得分配给它们的程序......到目前为止,我的代码只获得第一个带有#2的clientID ...

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

4 个答案:

答案 0 :(得分:3)

更改

if (reader.Read())

while (reader.Read())

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

答案 1 :(得分:1)

当然它只获得第一个结果,因为你只读了一次。 使用while(reader.Read())代替if(reader.Read())

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

答案 2 :(得分:1)

更改

if (reader.Read())

while(reader.Read())
旁注;如果您只需要单列数据,请不要使用select *,请使用select Coumnname from yourtable

答案 3 :(得分:0)

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

}