【发布时间】:2018-08-31 19:31:46
【问题描述】:
我目前正在创建一个具有 4 个按钮、一个更新、添加、删除和取消按钮的 Windows 窗体应用程序。我的记录中的信息直接进入我的文本框,我使用了SqlCommand cmd;。
我已经在我的添加按钮点击处理程序中添加了这个:
private void btnAdd_Click(object sender, EventArgs e)
{
if (true)
{
Utilities.ResetAllControls(this);
connection.Open();
cmd = new SqlCommand("insert into tblCar values('" + txtbxVehicleRegistrationNumber.Text + "','" + txtbxMake.Text + "','" + txtbxEngineSize.Text + "','" + txtbxDateRegistered + "','" + txtbxRentalPerDay + "','" + CbxAvailable.Checked + "')", connection);
MessageBox.Show("Your information has been successfully added.");
connection.Close();
}
}
列出的Utilities 是我创建的一个类。这是我添加数据的正确方法吗?此外,我想知道如何(在单击“添加”按钮后)为我从文本框中清除所有现有数据(但不删除它们)以添加新数据。如果有人帮助我解决我的这种困境,我将不胜感激。
Utilities 类是:
public class Utilities
{
public static void ResetAllControls(Control form)
{
foreach (Control control in form.Controls)
{
if (control is TextBox)
{
TextBox textBox = (TextBox)control;
textBox.Text = null;
}
if (control is ComboBox)
{
ComboBox comboBox = (ComboBox)control;
if (comboBox.Items.Count > 0)
comboBox.SelectedIndex = 0;
}
if (control is CheckBox)
{
CheckBox checkBox = (CheckBox)control;
checkBox.Checked = false;
}
if (control is ListBox)
{
ListBox listBox = (ListBox)control;
listBox.ClearSelected();
}
}
}
}
【问题讨论】:
-
你有一个 SQL 注入漏洞。
-
不,您不必使用 DBCommand 对象。 DataAdapter 消除了对它们(和连接对象)的需要。做什么取决于你在做什么
-
SQLCommand 通常用于 MSSQL,而不是 MySQL。
-
不要为 SQL 将字符串位粘合在一起。使用 SQL 参数。此处和 MSDN 上有关您正在使用的工具的大量帖子。 (请注意,TableAdapter 与 DataAdapter 不同)
标签: c# sql-server