如何使用c#更新数据库中的表

本文关键字:数据库 更新 何使用 | 更新日期: 2023-09-27 17:58:37

我的数据库中有一个名为"Members"的表。

在表单中,我有一些LabelsTextBoxesDataGridView和一些按钮。

当我单击DataGridView中的一行时,整个数据正确地显示在相应的TextBox中。

我添加了一个"更新"按钮,当点击它时,我希望数据库表信息立即更新。

我已经写了以下关于"更新"按钮点击事件的代码。但它不断地向我展示错误。请帮忙。我急需解决方案。

string Query = "UPDATE Members SET MemberID='" + MemberIDTextBox.Text + "'|| Name='" + NameTextBox.Text + "'|| Gender='" + GenderComboBox.Text + "'|| Address='" + AddressTextBox.Text + "'|| NID='" + NationalIDTextBox.Text + "'|| DOB='" + DOBTimePicker.Text + "'|| BloodGroup='" + BloodGroupTextBox.Text + "'|| Height='" + HeightTextBox.Text + "'|| Weight='" + WeightTextBox.Text + "'|| ChestSize='" + ChestSizeTextBox.Text + "'|| MusclesSize='" + MusclesSizeTextBox.Text + "'|| AbsPack='" + AbsPackTextBox.Text + "'|| Profession='" + ProfessionTextBox.Text + "'|| Contact='" + ContactTextBox.Text + "' WHERE MemberID='" + MemberIDTextBox.Text + "'";

SqlCommand Command = new SqlCommand(Query, Connection);
Command.ExecuteNonQuery();

如何使用c#更新数据库中的表

使用参数化查询:

SqlCommand cmd = new SqlCommand("update Members set Name=@Name, Gender=@Gender, Address=@Address, NID=@NID, DOB=@DOB, BloodGroup=@BloodGroup, Height=@Height, Weight=@Weight, ChestSize=@ChestSize, MusclesSizes=@MusclesSizes, AbsPack=@AbsPack, Profession=@Profession, Contact=@Contact" + " where MemberID=@MemberID", Connection);
cmd.Parameters.AddWithValue("@MemberID", MemberIDTextBox.Text);
cmd.Parameters.AddWithValue("@Name", NameTextBox.Text);
// ...
//Keep adding parameters
cmd.ExecuteNonQuery();

解决方案: 将双管(||)字符更改为逗号(,

像这样:

string Query = "UPDATE Members SET MemberID='" + MemberIDTextBox.Text + "',  Name='" + NameTextBox.Text + "',  Gender='" + GenderComboBox.Text + "',  Address='" + AddressTextBox.Text + "',  NID='" + NationalIDTextBox.Text + "',  DOB='" + DOBTimePicker.Text + "',  BloodGroup='" + BloodGroupTextBox.Text + "',  Height='" + HeightTextBox.Text + "',  Weight='" + WeightTextBox.Text + "',  ChestSize='" + ChestSizeTextBox.Text + "',  MusclesSize='" + MusclesSizeTextBox.Text + "',  AbsPack='" + AbsPackTextBox.Text + "',  Profession='" + ProfessionTextBox.Text + "',  Contact='" + ContactTextBox.Text + "' WHERE MemberID='" + MemberIDTextBox.Text + "'";

但是您应该真正考虑参数化查询。您只是在询问当前实现的SQL注入攻击。


如何使用参数化查询

关于StackOverflow,这里已经有一个解释得很好的答案,它给出了如何在代码中使用参数化查询的好例子。


什么是SQL注入

这是一段SQL代码本质上通过简单的字符串连接公开的地方——主要来自用户输入(文本字段等),就像在您的OP中一样。

如果在所述字段中输入恶意"查询",潜在的注入器可能会导致严重问题,并造成大量损坏,访问/编辑数据库中不应该访问的部分等。

当其他开发人员将他们的代码暴露在SQL注入中时,这不仅是世界上大多数程序员最讨厌的事情,而且是一个现实世界中的问题,它可能会(并且已经)摧毁业务。

SQL注入攻击实际上是"盲目的",但它们可能非常具有破坏性。


一些有用的资源

  • C-Sharp Corner的文章为您提供了更深入的描述SQL注入是什么以及如何防止它

  • 观看计算机爱好者的视频,了解运行SQL是多么容易(可怕)对暴露于的代码的注入攻击