我调用一个函数,该函数将 SqlDataReader
对象返回到调用语句。我很困惑应该在哪里关闭 SqlDataReader
对象和 SqlConnection
对象?在函数中还是在调用之后?
这是函数调用:
SqlDataReader dr2= RetrieveSearcher();
pid = dr2[0].ToString();
这是函数:
protected SqlDataReader RetrieveSearcher()
{
String Q = "select price from tb3 where pid='12';
cn = new SqlConnection("data source=.\\sqlexpress; integrated security=true; initial catalog=singh");
cn.Open();
cmd = new SqlCommand(Q,cn);
dr1 = cmd.ExecuteReader();
dr1.Read();
return dr1;
}
最佳答案
- 始终使用参数化查询以避免 SQL 注入(inject)攻击并提高性能(大多数数据库服务器可以通过适当的查询重用执行计划)
- 切勿让连接保持打开状态超过必要的时间!
- 不要共享数据库连接!创建它、使用它、销毁它。
- 将所有实现 IDisposable 的内容封装在
using
block 中,例如 Connections、Commands、DataReaders 等。这样可以确保即使在发生异常时也没有资源保持打开状态。 - 在数据库模式中使用正确的类型并读取这些类型,不要将所有内容与字符串进行全面转换!示例
price
看起来它实际上应该是十进制或数值,而不是字符串,因此不要将其存储为字符串,也不要将其作为字符串读回。 - 从 app.config 或 web.config(取决于应用程序类型)中按名称检索连接字符串,不要将字符串硬编码到您的连接或其他任何位置。
关于你的逻辑
更改您的方法以返回自定义类型,例如一段数据。这确保了正确的 SoS(关注点分离)。请勿退回 DataReader!这将从调用者那里抽象出整个数据库调用,这是您应该努力的目标。
protected SomeType RetrieveSearcherData(string pid)
{
const string Q = "SELECT price FROM tb3 WHERE pid = @pid";
using(var cn=new SqlConnection())
using(var cmd=new SqlCommand(Q,cn))
{
// I do not know what pid is but use tho correct type here as well and specify that type using SqlDbType
cmd.Parameters.Add(new SqlParameter("@pid", SqlDbType.VarChar, 100) { Value = pid});
cn.Open();
using(var dr1= cmd.ExecuteReader())
{
if(dr1.Read())
{
var result = dr1.GetDecimal(0);
// read something and return it either in raw format or in some object (use a custom type)
}
else
return null; // return something else that indicates nothing was found
}
}
}
关于c# - 在哪里关闭SqlDataReader对象和SqlConnection对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42447473/