有没有办法优化下面的代码。我使用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个?
答案 0 :(得分:0)
您可能希望在一个阅读器中使用多个结果集。
答案 1 :(得分:0)
'; DROP TABLE deliveryphone
会发生什么。using
块中,以便它们在超出范围时关闭/丢弃。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
}
}
}