繁体   English   中英

从数据库中删除一条记录

[英]Delete a record from database

我试图通过输入 ID 并点击删除 btn 从数据库 MSSQL 中删除记录。 我没有收到任何错误,并且成功删除了记录,但是一旦我检查数据库,我就会看到记录没有删除

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";
    }
}
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 块中的所有好东西,您永远不会知道为什么在执行此查询后查询失败。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM