SqlDataReader的问题,高手请帮帮忙
我是一个新手,刚刚接触asp.net,看到了SqlDataReader但不太会用,请教.
private void GetInspector()
{
SqlConnection cn = new SqlConnection(ClassTools.SQL.Connect());
SqlCommand cmd = new SqlCommand( "Web_User_GetInspector ",cn);
cmd.CommandType = CommandType.StoredProcedure;
try
{
cn.Open();
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
Inspector.DataSource = dr;//下拉菜单的数据控件
Inspector.DataBind();
}
catch(Exception ex)
{
Response.Write(ex.Message);
}
finally
{
cn.Close();
cmd.Dispose();
cn.Dispose();
}
}
private void GetInfo(string ID)
{
SqlConnection cn = new SqlConnection(ClassTools.SQL.Connect());
SqlCommand cmd = new SqlCommand( "Web_Item_GetInfo ",cn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add( "@ItemNumber ",SqlDbType.NVarChar,50);
cmd.Parameters[0].Value = ID;
try
{
cn.Open();
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if(dr.Read())
{
Reber.Text = dr[ "Reber "].ToString();
Orber.Text = dr[ "Orber "].ToString();
Itber.Text = dr[ "Itber "].ToString();
}
}
catch(Exception ex)
{
Response.Write(ex.Message);
}
finally
{
cn.Close();
cmd.Dispose();
cn.Dispose();
}
}
请问上面两个函数写的对吗,用在并发中能不能出错误,如果出错,应该怎么改,还有我不知道我写的函数中SqlDataReader怎么关闭,在哪关闭,还有就是finally
里写的代码的位置是否正确,是不是先关闭连接再释放对象,在线等.
------解决方案--------------------try
{
cn.Open();
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
Inspector.DataSource = dr;//下拉菜单的数据控件
Inspector.DataBind();
dr .Close();
}
catch(Exception ex)
{
Response.Write(ex.Message);
}
finally
{
cn.Close();
cmd.Dispose();
cn.Dispose();
}
try
{
cn.Open();
SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if(dr.Read())
{
Reber.Text = dr[ "Reber "].ToString();
Orber.Text = dr[ "Orber "].ToString();
Itber.Text = dr[ "Itber "].ToString();
}
dr.Close();