【发布时间】:2018-05-04 15:21:58
【问题描述】:
有没有办法优化下面的代码。我正在使用 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个?
【问题讨论】:
-
如果您的代码有效,但您需要如何优化它的建议,请将您的问题移至Code Review 网站。
-
1) 谷歌sql how to join tables。这将帮助您了解如何创建单个查询来获取所需的所有数据。 2) 始终为您的值使用参数!请参阅How can I add user-supplied input to an SQL statement?,了解如何参数化您的查询。如果您认为这不重要,如果有人在
textBox1.Text中输入文本值'; DROP TABLE deliveryphone会发生什么。 -
首先,您正在创建一个巨大的安全漏洞……请改用存储过程。第二次将sql重写为join,这样就不必处理多个记录集了。
-
@BillRuhl 不需要存储过程。他需要使用参数化查询。
-
@amy 我没有说存储过程是必要的,是的,使用存储过程更安全,而且是参数化查询。
标签: c#