2012-10-18 48 views
0

我一直在尝试将参数添加到循环内的存储过程。下面给出的是我声明我的变量的代码。C#:将参数添加到循环内的存储过程

SqlConnection con = new SqlConnection(); 
     Connect conn = new Connect(); 
     SqlDataReader readerCourseID = null; 
     con = conn.getConnected(); 
     con.Open(); 
     SqlCommand cmdAssignCourse; 
     cmdAssignCourse = new SqlCommand("assignCourse", con); 
     cmdAssignCourse.CommandType = CommandType.StoredProcedure; 
     cmdAssignCourse.Parameters.Add("@sID", System.Data.SqlDbType.VarChar); 
     cmdAssignCourse.Parameters.Add("@cID", System.Data.SqlDbType.VarChar); 
     SqlParameter retValue = cmdAssignCourse.Parameters.Add("return", System.Data.SqlDbType.Int); 

而下面是我将值插入前面声明的变量的代码。

foreach (DataRow row in dt.Rows) 
      { 
       //get course id from course name. Pass row["Course Name"].ToString() 
       int i = getCourseID(row["Course Name"].ToString()); 



       //assignment of the course to student 
       cmdAssignCourse.Parameters["@sID"].Value = studentCurrID.Value.ToString(); 
       cmdAssignCourse.Parameters["@cID"].Value = i; 
       retValue.Direction = ParameterDirection.ReturnValue; 
       cmdAssignCourse.ExecuteNonQuery(); 
       if (retValue.Value.ToString() == "0") 
       { 
        MessageBox.Show("Added Course Successfully!"); 
        //return 0; 
       } 
       else 
       { 
        MessageBox.Show("An error occured! Possibly a duplication of data!"); 
        //return -1; 
       } 

      } 

但是,此代码运行成功并显示消息“已成功添加课程!”一旦。但在第一次成功运行后,每隔一次运行它就会给我“发生错误!可能是重复的数据!”信息。可能的错误不会清除变量。如何清除下面的变量。请帮我解决一下这个。谢谢!

+0

尝试使用SqlServer的Profiler来看看你的代码发送到数据库是正确的。这会让你知道你的参数值是否改变。 – RePierre

+0

你确定数据表dt中没有重复条目吗?为什么你将整数作为varchars传递? – podiluska

回答

1

您没有通过重新使用相同的SqlCommand和SqlConnection获得任何东西。连接池将为您完成所有艰苦的工作,无需重新发明轮子。这将是更清晰,更健壮分离出你的代码,所以创建一个新的方法来执行的过程:

private int GenerateReturnValue(int courseID, int studentID) 
{ 
    using (var connection = new SqlConnection("Your Connection String")) 
    using (var command = new SqlCommand("assingCourse", connection) 
    { 
     connection.Open(); 
     command.CommandType = CommandType.StoredProcedure; 
     command.Parameters.Add("@sID", System.Data.SqlDbType.VarChar).Value = studentID.ToString(); 
     command.Parameters.Add("@cID", System.Data.SqlDbType.VarChar).Value = courseID.ToString(); 
     command.Parameters.Add("@Return", System.Data.SqlDbType.Int).Direction = ParameterDirection.ReturnValue; 
     command.ExecuteNonQuery(); 

     return (int)command.Parameters["@Return"].Value; 
    } 
} 

然后,只需调用该方法在循环。

foreach (DataRow row in dt.Rows) 
{ 
    int i = GenerateReturnValue(getCourseID(row["Course Name"].ToString()), studentCurrID.Value); 
    if (i = 0) 
    { 
     MessageBox.Show("Added Course Successfully!"); 
     //return 0; 
    } 
    else 
    { 
     MessageBox.Show("An error occured! Possibly a duplication of data!"); 
     //return -1; 
    } 
} 

另外我觉得James地说,问题在于这样一个事实:you never re-pull the return value from the query, you are missing that line after execution: