从数据库删除记录

时间:2019-04-15 19:19:51

标签: c# sql asp.net database

我正在尝试通过输入ID从数据库MSSQL删除记录并点击Delete btn。我没有收到任何错误,它成功删除了记录,但是一旦我检查了数据库,我发现记录没有被删除

protected void btnDelete_Click(object sender, EventArgs e)
{
    try
    {
        if (txtImgID.Text == "")
        {

            Response.Write("Enter Image Id To Delete");
        }
        else
        {
            SqlCommand cmd = new SqlCommand();
            SqlConnection con = new SqlConnection();

            con = new SqlConnection(ConfigurationManager.ConnectionStrings["GMSConnectionString"].ConnectionString);

            con.Open();
            cmd = new SqlCommand("delete from certf where id=" + txtImgID.Text + "", con);

            lblsubmitt.Text = "Data Deleted Sucessfully";
        }
    }

    catch (Exception)
    {
        lblsubmitt.Text = "You haven't Submited any data";
    }
}

1 个答案:

答案 0 :(得分:0)

var idToDelete = int.Parse(txtImgID.Text); // this is not necessary if the data type in the DB is actually a string

using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["GMSConnectionString"].ConnectionString))
using (SqlCommand cmd = new SqlCommand("DELETE FROM [certf] WHERE id = @id", con))
{
  // I am assuming that id is an integer but if it is a varchar/string then use the line below this one
  // cmd.Parameters.Add("@id", SqlDbType.VarChar, 100).Value = txtImgID.Text;
  cmd.Parameters.Add("@id", SqlDbType.Int32).Value = idToDelete;
  cmd.ExecuteNonQuery();
}
  1. 您需要调用ExecuteNonQuery来对数据库执行查询。
  2. 在查询中始终使用参数而不是字符串连接。它可以防止sql注入,并确保您永远不会出现包含转义符的字符串的问题。
  3. 我没有包含任何错误处理或返回消息,但请注意,您正在扔掉处理程序的catch块中的所有好东西,执行此查询后,您将永远不知道为什么查询失败。