我正在尝试执行查询以在给定ID的情况下从我的数据库中删除书籍记录。当我单击删除按钮时,出现以下错误:
ExecuteNonQuery:尚未初始化Connection属性。
到目前为止我的代码是:
private void btnDelete_Click(object sender, EventArgs e)//delete book
{
SqlCommand com = new SqlCommand("DELETE FROM [tbl_Book] WHERE Book_ID='"+txtBookID.Text+"'");
cn.Open();
com.ExecuteNonQuery();
cn.Close();
MessageBox.Show("Book Deleted Successfully", "System", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
答案 0 :(得分:0)
您必须初始化新的sql connection
并将其传递给Sql command object
。
private void btnDelete_Click(object sender, EventArgs e)
{
Sqlconection connection = new Sqlconection("Your Connection String Here");
connection.Open();
SqlCommand com = new SqlCommand("DELETE FROM [tbl_Book] WHERE Book_ID='"+txtBookID.Text+"'", connection);
com.ExecuteNonQuery();
connection.Close();
MessageBox.Show("Book Deleted Successfully", "System", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
希望这会有所帮助......
答案 1 :(得分:0)
您没有绑定command with connection
。你可以在构造函数中做到。
SqlCommand com = new SqlCommand("Your Query", connection);