这看起来很傻但我不能指责这个。我在这做错了什么?这是一个常见的错误,但我似乎没有像在这里的其他几十个帖子上犯同样的错误...
public static string Insert(SqlCommand cmd, SqlConnection connection)
{
//feedback to user on whether the insert was successful
string success = "Success! Thank you for contributing to this project";
int added = 0;
//connect and insert the data
try
{
using (connection)
{
connection.Open();
added = cmd.ExecuteNonQuery();
//update success variable
success += "\n" + added.ToString() + " records inserted.";
}//end using(connection)
}//end try
catch (Exception err)
{
//if we have an error, return this message for debugging purposes for now
string message = err.Message;
return message;
}//end catch
return success;
}//end Insert()
答案 0 :(得分:3)
您的Command
对象可能没有连接,因为您将Connection
和Command
传递给您的方法。您需要将连接分配给命令对象属性Connection
。
try
{
using (connection)
{
cmd.Connection = connection; //Here assign connection to command object
connection.Open();
added = cmd.ExecuteNonQuery();
//update success variable
success += "\n" + added.ToString() + " records inserted.";
}//end using(connection)
}//end try