日期:2014-05-17  浏览次数:20851 次

已有打开的与此命令相关联的 DataReader,必须首先将它关闭
C# code

public void Export_Click(object sender, EventArgs e)
{
        string sqlString = "server=.\\SQL2005;database=stu_info;uid=sa;pwd=123456";
        try
        {
            SqlConnection sqlconn = new SqlConnection(sqlString);
            sqlconn.Open();
            string sql = "SELECT A.id,A.name,B.title FROM person AS A JOIN book AS B ON A.id=B.id";
            SqlCommand cmd = new SqlCommand(sql, sqlconn);
            SqlDataReader reader = cmd.ExecuteReader();
            string insql;
            while (reader.Read())
            {
                insql = "INSERT INTO lh VALUES('" + reader[0] + "','" + reader[1] + "','" + reader[2] + "')";
                SqlCommand incmd = new SqlCommand(sql, sqlconn);
                incmd.ExecuteNonQuery();
            }
        }
        catch (SqlException ex)
        {
            string MsgEx = ex.Message;
            MsgExport.Visible = true;
            MsgExport.Text = MsgEx;
        }
    }


上面代码在调试时
到这一行:
C# code
incmd.ExecuteNonQuery();

提示:{"已有打开的与此命令相关联的 DataReader,必须首先将它关闭。"}
请问下这个函数应该怎么写才能避免这个问题,又能实现想要的功能?

------解决方案--------------------
当然也可以稍微简化一点
C# code

        string sqlString = "server=.\\SQL2005;database=stu_info;uid=sa;pwd=123456";
        using(SqlConnection sqlconn = new SqlConnection(sqlString))
        using(SqlConnection sqlconn2 = new SqlConnection(sqlString))
        {
            sqlconn.Open();
            sqlconn2.Open();
            string sql = "SELECT A.id,A.name,B.title FROM person AS A JOIN book AS B ON A.id=B.id";
            SqlCommand cmd = new SqlCommand(sql, sqlconn);
            SqlDataReader reader = cmd.ExecuteReader();
            string insql;
            SqlCommand incmd = sqlconn2.CreateCommand();
            while (reader.Read())
            {
                insql = "INSERT INTO lh VALUES('" + reader[0] + "','" + reader[1] + "','" + reader[2] + "')";
                incmd.CommandText= insql;
                incmd.ExecuteNonQuery();
            }
        }