asp.net DataReader 永不关闭

asp.net DataReader never close

if manage_score return true ,函数Update被调用。 在 Update(System.Data.SqlClient.SqlDataReader oReader3 = cmd2.ExecuteReader() 的这一行。我得到这个错误(已经有一个打开的 DataReader 与这个命令关联,必须先关闭。)我删除了一些行来制作代码阅读时间更短。 Manage_score:插入一个新条目(如果不存在)。 更新:如果条目已经存在则调用,并在更新之前进行一些计算。

谢谢

public static bool manage_score(String City, String Street, String No, int Clean, int Fun, int Study, bool recommend)
{
    System.Data.SqlClient.SqlConnection conn=null;
    System.Data.SqlClient.SqlCommand cmd = null; ;
    System.Data.SqlClient.SqlDataReader rdr=null;
    bool needUpdate=false;

    try
    {
        using( conn = new System.Data.SqlClient.SqlConnection(dbConn))
        { 

             using(cmd = new System.Data.SqlClient.SqlCommand(
             "Insert Into c_Show (Street,City,No,Count,Clean,Fun,Study,CleanScore,FunScore,StudyScore,Like_,Dislike) " +
             "VALUES (@Street,@City,@No,'1',@Clean,@Fun,@Study,@Clean,@Fun,@Study,@Like,@DisLike)", conn))
             { 
                cmd.Parameters.Add("@No", System.Data.SqlDbType.Int).Value = No;
                cmd.Parameters.Add("@City", System.Data.SqlDbType.Char).Value = City;

                cmd.Connection.Open();
                using (rdr = cmd.ExecuteReader(System.Data.CommandBehavior.CloseConnection)) { }
            }
        }
    }
    catch (System.Data.SqlClient.SqlException ex)
    {
        if (ex.Number == 2627)// duplicate key
        {
            needUpdate=true;
        }
    }
    catch (System.Exception ex) { }

    return needUpdate;
}

static public void update(String City, String Street, String No, int Clean, int Fun, int Study, bool recommend)
{
    using (System.Data.SqlClient.SqlConnection conn2 = new System.Data.SqlClient.SqlConnection(dbConn))
    {
        String resCount = null;
        String resClean = null;
        String resFun = null;
        String resStudy = null;
        String resLike = null;
        String resDislike = null;

        using (System.Data.SqlClient.SqlCommand cmd2 = new System.Data.SqlClient.SqlCommand(
        "SELECT Street,City,No,Count,CleanScore,FunScore,StudyScore,Like_,Dislike FROM c_Show " +
        "Where City=@City and Street=@Street and No=@No ", conn2))
        {
            cmd2.Parameters.Add("@No", System.Data.SqlDbType.Int).Value = No;
            cmd2.Parameters.Add("@City", System.Data.SqlDbType.Char).Value = City;
            cmd2.Parameters.Add("@Street", System.Data.SqlDbType.NVarChar).Value = Street;
            cmd2.Connection.Open();
            cmd2.ExecuteReader();
            using (System.Data.SqlClient.SqlDataReader oReader3 = cmd2.ExecuteReader())
            {}
        }
    }
}

根据您的代码,您错误地调用了 cmd2.ExecuteReader() 两次。

        cmd2.ExecuteReader(); // once.  You probably want to remove this one?
        using (System.Data.SqlClient.SqlDataReader oReader3 = cmd2.ExecuteReader()) // twice
        {

我认为第一个电话是个错误。删除它,你应该没问题。