问题描述
- 关于c#的dr.Close();放哪里好?
-
cn.ConnectionString = "server = (local);password = 123;uid = sa;database = keshe"; cn.Open(); SqlCommand cmd_jiage = new SqlCommand("select 出租价格 from 房屋表", cn); SqlDataReader dr = cmd_jiage.ExecuteReader(); while (dr.Read()) { if (dr["出租价格"].ToString().Trim() == TextBox1.Text) { SqlCommand cmd = new SqlCommand("select * from 房屋表 where 出租价格 = @jiage", cn); cmd.Parameters.Add("@jiage", TextBox1.Text); GridView1.DataSource = cmd.ExecuteReader(); GridView1.DataBind(); } else { Label1.Text = "asd"; } dr.Close(); } cn.Close();
解决方案
使用
using (SqlDataReader dr = cmd_jiage.ExecuteReader()) {
while(dr.Read()) {
// do the readings.....
}
} // will be automatically disposed here, no Close is needed
时间: 2024-12-27 12:59:23