c# - 从数据库中删除一条记录
问题描述
我正在尝试通过输入 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();
}
- 您需要调用对数据库执行查询的ExecuteNonQuery 。
- 在查询中始终使用参数而不是字符串连接。它可以防止 sql 注入并确保您永远不会遇到包含转义字符的字符串的问题。
- 我没有包含任何错误处理或返回消息,但请注意您正在丢弃异常处理程序的 catch 块中的所有好东西,您永远不会知道为什么在执行后查询失败。
推荐阅读
- google-cloud-platform - 我的构建触发器无法识别 glob 模式
- python - PyQt6获取QTreeWidgetItem的父窗口?
- android - 如何知道用户点击了哪个按钮及其在 Android Studio 中的文本和 ID?
- python - 如何计算时间轴上重复次数最多的值的出现次数?- Xarray 蟒蛇
- javascript - Vue.js - 从 API 获取数据并在 Vuex 状态更改时重新加载组件
- javascript - 如何制作表格页面?
- sql - 在子查询中使用 MAX 的 SQL
- dynamic - BI Publisher RTF 模板中的动态超链接
- kubernetes - 如何查看 Kubernetes 上的所有可用资源?
- html - 您能否为具有特定类型字母的最少数量的 HTML 输入字段创建模式?