我正在尝试一个例子。我在db中有一个名为Deleted的字段。 。当我点击删除按钮实际上没有删除数据只是重复“N”与“Y”值问题是我下载源代码它工作但稍微改变后我得到这个例外。我想知道我做错了什么
此代码有效
if (e.CommandName.Equals("Delete"))
{
long holidayNum = Convert.ToInt64(e.CommandArgument);
using (SqlConnection con = new SqlConnection())
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.Parameters.Add("@Deleted", SqlDbType.NChar).Value = "Y";
cmd.CommandText = "Update HolidaysDetails set Deleted=@Deleted where HolidayNum=" + holidayNum;
con.ConnectionString = connectionString;
cmd.Connection = con;
if (con.State == ConnectionState.Closed)
{
con.Open();
}
int result = cmd.ExecuteNonQuery();
con.Close();
dlHoliday.EditItemIndex = -1;
GetData();
}
}
}
但我的代码抛出异常
if (e.CommandName.Equals("delete"))
{
long holidayNum = Convert.ToInt64(e.CommandArgument);
cmdText = "Update HolidaysDetails set Deleted=@deleted where HolidayNum"
+ holidayNum;
using (con = new SqlConnection(cnnStr))
{
if (con.State == ConnectionState.Closed)
{
con.Open();
}
using (cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandText = cmdText;
cmd.Parameters.AddWithValue("@deleted", SqlDbType.NChar).Value = "Y";
cmd.ExecuteNonQuery();
con.Close();
dlHoliday.EditItemIndex = -1;
GetData();
}
}
}
答案 0 :(得分:2)
只是错过了这里的等号
cmdText = "Update HolidaysDetails set Deleted=@deleted " +
"where HolidayNum=" + holidayNum;
^
顺便说一句,当您尝试遵循正确的做法并使用@deleted
标志的参数时,您做错了。作为第二个参数,AddWithValue要求值不是参数类型。修复它时,还要添加查询所需的第二个参数
cmdText = "Update HolidaysDetails set Deleted=@deleted " +
"where HolidayNum=@num";
......
cmd.Connection = con;
cmd.CommandText = cmdText;
cmd.Parameters.AddWithValue("@deleted", "Y");
cmd.Parameters.AddWithValue("@num", holidaynum);
cmd.ExecuteNonQuery();
....