在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;
    }