我,我正在设计一个CMS(校园管理系统),我想删除一些记录......但它既不工作也不产生任何错误......只需在代码中提到的“结果”变量中返回零
public void DeleteAnnouncement(BusinessObject bo)
{
string ConnStr = Connection();
SqlConnection conn = new SqlConnection(ConnStr);
conn.Open();
string query = "Delete from Anouncement where AnnouncementID=@i";
SqlCommand cmd = new SqlCommand(query, conn);
SqlParameter p1 = new SqlParameter("i", bo.A_ID);
cmd.Parameters.Add(p1);
int result = cmd.ExecuteNonQuery();
conn.Close();
if (result > 0)
{
Console.WriteLine("\n\n\t============================================");
Console.WriteLine("\tAnnouncement Deleted");
Console.WriteLine("\t============================================\n\n");
}
}
答案 0 :(得分:0)
SqlParameter p1 = new SqlParameter("i", bo.A_ID);
你在参数名称前面缺少“@”。
Correct: SqlParameter p1 = new SqlParameter("@i", bo.A_ID);
答案 1 :(得分:0)
如果Anouncement
与AnnouncementID
的值匹配,如果bo.A_ID
的值与bo.A_ID
不匹配,则您的代码将从AnnouncementID
表中删除记录并删除记录cmd.ExecuteNonQuery();
,0
返回AnnouncementID
。如果没有删除,则表示bo.A_ID
与using
的值不匹配。
但我建议通过using
语句改进代码,这个string ConnStr = Connection();
string query = "Delete from Anouncement where AnnouncementID=@i";
using (SqlConnection conn = new SqlConnection(ConnStr))
{
using (SqlCommand cmd = new SqlCommand(query, conn))
{
try
{
SqlParameter p1 = new SqlParameter("i", bo.A_ID);
cmd.Parameters.Add(p1);
conn.Open();
int result = cmd.ExecuteNonQuery();
conn.Close();
if (result > 0)
{
Console.WriteLine
("\n\n\t============================================");
Console.WriteLine("\tAnnouncement Deleted");
Console.WriteLine
("\t============================================\n\n");
}
}
catch (Exception ex)
{
//Do your exception handling work
}
}
}
语句确保即使在调用对象上的方法时发生异常也会调用Dispose。
static void Main(string[] args)
{
EFTest t = new EFTest();
t.Test();
}