多个ExecuteReader优化

时间:2018-05-04 15:21:59

标签: c#

有没有办法优化下面的代码。我使用3个executeReader来获得不同的结果

SqlCommand command = new SqlCommand("select DeliveryID,Name from deliveryphone WHERE PhoneNumber= '" + textBox1.Text + "'", con);
        SqlDataReader read = command.ExecuteReader();

        while (read.Read())
        {

            SqlDeliveryID = (read["DeliveryID"].ToString());
            textBox2.Text = (read["Name"].ToString());

        }
        read.Close();
        SqlCommand command2 = new SqlCommand("select  Adress from DeliveryAdress WHERE DeliveryID= '" + SqlDeliveryID + "' ", con);
        SqlDataReader read2 = command2.ExecuteReader();

        while (read2.Read())
        {
            comboBox1.Items.Add(read2["Adress"].ToString());

        }
        read2.Close();
        SqlCommand command3 = new SqlCommand("select top 1 Adress,Location,Floor,Comments from DeliveryAdress WHERE DeliveryID= '" + SqlDeliveryID + "' order by DefaultAdress desc", con);
        SqlDataReader read3 = command3.ExecuteReader();

        while (read3.Read())
        {
            comboBox1.Text = (read3["Adress"].ToString());
            textBox3.Text = (read3["Location"].ToString());
            comboBox2.Text = (read3["Floor"].ToString());
            textBox5.Text = (read3["Comments"].ToString());

        }

有没有办法将这3个读者合并为1个?

2 个答案:

答案 0 :(得分:0)

您可能希望在一个阅读器中使用多个结果集。

How to read multiple resultset from SqlDataReader?

答案 1 :(得分:0)

  1. Google sql how to join tables,这将帮助您了解如何创建单个查询以获取所需的所有数据。
  2. 始终为您的值使用参数!请参阅如何将用户提供的输入添加到SQL语句中?如何参数化您的查询。如果您认为这不重要,如果有人在textBox1.Text中输入文本值'; DROP TABLE deliveryphone会发生什么。
  3. 将您的一次性用品包裹在using块中,以便它们在超出范围时关闭/丢弃。
  4. const string query = @"SELECT dp.DeliveryID, dp.Name, da.Adress, da.Location, da.Floor, da.Comments
        FROM DeliveryPhone dp INNER JOIN DeliveryAdress da ON dp.DeliveryID = da.DeliveryID
        WHERE dp.PhoneNumber=@phoneNumber";
    
    
    using(SqlCommand command = new SqlCommand(query, con))
    {
      // I guessed on the sql type and length
      command.Parameters.Add(new SqlParameter("@phoneNumber", SqlDbType.VarChar, 50) {Value = textBox1.Text});
      con.Open(); // is the connection always open? Really you should create connections on an as needed basis and then dispose of them
      using(SqlDataReader read = command.ExecuteReader())
      {
        if(reader.Read())
        {
          textBox2.Text = read.GetString(1);
          comboBox1.Text = read.GetString(2);
          textBox3.Text = read.GetString(3);
          comboBox2.Text = read.GetString(4);
          textBox5.Text = read.GetString(5);
          // if you need the other values you can get those as well
        }
      }
    }