我有下面的代码可以从存储过程中查询记录,但我担心我可能没有处理我需要的东西,或者当对象很快就会被垃圾收集器清除时我正在处理。
我是否需要处理 SqlDataReader,因为它在 try catch block 中?
我需要同时运行 cmd.Dispose 和 cmd.Connection.Close 还是一个推断另一个?
垃圾收集器最终是否会处理所有这些对象(可能不够及时),或者这些对象是否可能因为使用非托管代码而隐含地需要处理?
public void GetData(string studentID)
{
SqlCommand cmd = new SqlCommand("sp_stored_proc",
new SqlConnection(Settings.Default.connectionString))
{ CommandType = CommandType.StoredProcedure };
try
{
cmd.Connection.Open();
cmd.Parameters.AddWithValue("@student_id", studentID);
SqlDataReader dr = cmd.ExecuteReader();
//do something with the data
if (dr != null)
dr.Dispose();
}
catch
{
//error handling
}
finally
{
if (cmd != null)
{
cmd.Dispose();
cmd.Connection.Close();
}
}
}
最佳答案
您应该处理数据读取器和命令。如果处理命令,则无需单独关闭连接。理想情况下,您应该使用 using
block 来完成这两项操作:
using (SqlCommand cmd = new...)
{
// do stuff
using (SqlDataReader dr = cmd.ExecuteReader())
{
// do stuff
}
}
如果您需要异常处理,请在 using block 内部或周围单独执行 - 尽管使用 using
调用 Dispose
不需要 finally。
关于c# sql 要处理什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1158665/