在C#中使用Retun,并访问数据库时应注意犯的错误
来源:互联网 发布:java方法调用 参数返回 编辑:程序博客网 时间:2024/05/29 08:05
下面这段程序逻辑上是有错误的,它造成的直接后果是SqlConnection和SqlDataReader对象的实例无法正常关闭,以致致数据库连接超时,而无法访问数据库.
public bool CheckQSID(string strQSID)
{
string sqlSelect = "select count(qsid) from xkzsqsid where qsid='" + strQSID + "'";
SqlConnection myconn;
myconn = new SqlConnection(ConfigurationManager.ConnectionStrings
["BaseConnectionString"].ConnectionString);
myconn.Open();
SqlCommand mycmd = new SqlCommand(sqlSelect, myconn);
SqlDataReader myreader = mycmd.ExecuteReader();
if (myreader.Read())
{
if (Convert.ToInt32(myreader[0]) > 1)
return true;
else
return false;
}
else
{
return false;
}
myreader.Close();
myconn.Close();
}
修改代码如下:
public bool CheckQSID(string strQSID)
{
string sqlSelect = "select count(qsid) from xkzsqsid where qsid='" + strQSID + "'";
SqlConnection myconn;
myconn = new SqlConnection(ConfigurationManager.ConnectionStrings
["BaseConnectionString"].ConnectionString);
myconn.Open();
SqlCommand mycmd = new SqlCommand(sqlSelect, myconn);
SqlDataReader myreader = mycmd.ExecuteReader();
try
{
if (myreader.Read())
{
if (Convert.ToInt32(myreader[0]) > 1)
return true;
else
return false;
}
else
{
return false;
}
}
finally
{
myreader.Close();
myconn.Close();
}
}
或者修改如下:
public bool CheckQSID(string strQSID)
{
bool bReurnValue;
string sqlSelect = "select count(qsid) from xkzsqsid where qsid='" + strQSID + "'";
SqlConnection myconn;
myconn = new SqlConnection(ConfigurationManager.ConnectionStrings["BaseConnectionString"].ConnectionString);
myconn.Open();
SqlCommand mycmd = new SqlCommand(sqlSelect, myconn);
SqlDataReader myreader = mycmd.ExecuteReader();
if (myreader.Read())
{
if (Convert.ToInt32(myreader[0]) > 1)
bReurnValue=true;
else
bReurnValue=false;
}
else
{
bReurnValue=false;
}
myreader.Close();
myconn.Close();
return bReurnValue;
}
- 在C#中使用Retun,并访问数据库时应注意犯的错误
- 错误2error LNK2005: *已经在 *.obj 中定义(使用多个.cpp文件时,应注意的事项)
- 在JSP中使用SmartUpload下载应注意的问题
- jquery在IE中使用append应注意的问题
- jquery在IE中使用append应注意的问题
- 在nhibernate 1.2 中使用sqlite时应注意sqlite的ado.net的提供者
- StoryBoard中通过连线跳转的控制器在使用时应注意的事项
- 数据库开发中应注意的地方
- 数据库设计中应注意的问题
- 数据库设计中应注意的问题
- 编程时常犯的几个错误、应注意的事项以及技巧
- 在构造函数中使用new时应注意的事项
- 在SQL Server 2008 中使用DECLARE-SELECT时应注意的细节
- 在构造函数中使用new时应注意的事项
- 在构造函数中使用new时应注意的事项
- 在构造函数中使用new时应注意的事项、析构函数调用
- 在构造函数中使用new时应注意的事项
- 在构造函数中使用new时应注意的事项
- 跟陌生人逛街的周末
- 图书在线看
- 《老子》
- left-to-right evaluation rule and side effect
- 在Netscape中,event.target 不能在函数中调用的问题
- 在C#中使用Retun,并访问数据库时应注意犯的错误
- 第一次亲密接触
- [转载]C++ STL(标准模板库) 学习资源列表
- oracle最常规问题和方法
- SQL 的一些常见函数
- GSM无线模块短消息PDU 格式说明
- ZZ最近做了温水煮青蛙的试验 感觉真的上当了
- EXCEL VBA中報1004錯誤
- 未来