string sqlstrStudent = "select * from Student where ClassName='" + this.DropDownListCl.SelectedValue .ToString ()+ "'";
SqlCommand commStudent = new SqlCommand(sqlstrStudent, conn);
using (SqlDataReader reader = commStudent.ExecuteReader())
{
while (reader.Read())
{
string sqlstrStuCous = "insert into Student_Course(StudentID,CourseName,TchID)values('" + reader["StudentID"] + "','" + this.txtName.Text + "','" + Session["UserID"] + "')";
SqlCommand commStuCous = new SqlCommand(sqlstrStuCous, conn);
commStuCous.ExecuteNonQuery(); }
}
为啥还是提示未关闭datareader呢求各位大大解决……
SqlCommand commStudent = new SqlCommand(sqlstrStudent, conn);
using (SqlDataReader reader = commStudent.ExecuteReader())
{
while (reader.Read())
{
string sqlstrStuCous = "insert into Student_Course(StudentID,CourseName,TchID)values('" + reader["StudentID"] + "','" + this.txtName.Text + "','" + Session["UserID"] + "')";
SqlCommand commStuCous = new SqlCommand(sqlstrStuCous, conn);
commStuCous.ExecuteNonQuery(); }
}
为啥还是提示未关闭datareader呢求各位大大解决……
using (SqlDataReader reader = commStudent.ExecuteReader())
{
// 最后都加上一句
reader.close();
}
改为SqlDataReader reader = commStudent.ExecuteReader(CommandBehavior.CloseConnection);
这样你试下看看
我还有别的sqlcommand语句,是不是也要加上using啊?
using (SqlConnection cn = new SqlConnection(“”))
{
SqlCommand cmd1 = new SqlCommand("", cn);
cn.Open();
using (SqlDataReader dr1 = cmd1.ExecuteReader())
{
while (dr1.Read())
{
string sql= "";
SqlConnection conn2 = new SqlConnection("");
SqlCommand cmd2 = new SqlCommand(sql, conn2 );
cmd2.ExecuteNonQuery();
}
} }
while (reader.Read())
{
string sqlstrStuCous = "insert into Student_Course(StudentID,CourseName,TchID)values('" + reader["StudentID"] + "','" + this.txtName.Text + "','" + Session["UserID"] + "')";
SqlCommand commStuCous = new SqlCommand(sqlstrStuCous, conn);
commStuCous.ExecuteNonQuery(); }
在这个循环里面SqlDataReader对象 reader是一直连接着没有关闭的,所以报错。改下。ArrayList temp=new ArrayList();
while (reader.Read())
{
string str=reader["StudentID"].ToString();
temp.Add(str); }foreach(string s in temp)
{
string sqlstrStuCous = "insert into Student_Course(StudentID,CourseName,TchID)values('" + s + "','" + this.txtName.Text + "','" + Session["UserID"].ToString() + "')";
SqlCommand commStuCous = new SqlCommand(sqlstrStuCous, conn);
commStuCous.ExecuteNonQuery();
}
while (reader.Read())
{
string str=reader["StudentID"].ToString();
temp.Add(str); }
之后加上reader.close()才可以哦。谢谢啦,为什么 这样可以啊,我想不太明白