我需要在单击按钮时从访问数据库中删除某些数据并且它一直抛出与executeNonquery()相关的错误,我真的很新,我会很感激任何帮助,这是我的代码
private void btnDelete_Click(object sender, EventArgs e)
{
OleDbConnection myDb = new OleDbConnection(connectionString + DBFile);
myDb.Open();
if (ComboBoxSelection.SelectedIndex == 0)
{
OleDbCommand command = new OleDbCommand();
command.Connection = myDb;
foreach (DataGridViewRow myRow in dataGridView1.SelectedRows)
{
string query = "DELETE FROM Clients WHERE ClientID = '{int.Parse(txtEdit.text)}'";
command.CommandText = query;
}
command.ExecuteNonQuery();
myDb.Close();
}
else if (ComboBoxSelection.SelectedIndex == 1)
{
OleDbCommand command = new OleDbCommand();
command.Connection = myDb;
foreach (DataGridViewRow myRow in dataGridView1.SelectedRows)
{
string query = "DELETE FROM Clients WHERE ClientID = '{txtEdit.text}'";
command.CommandText = query;
}
command.ExecuteNonQuery();
myDb.Close();
}
}
答案 0 :(得分:2)
对您要执行的操作做了很多假设,即从数据库中删除所选行中的每个客户端ID。这是一个很大的假设,因为你在每行的示例代码中使用相同的TextBox
,但我猜这是一项正在进行中的工作,你最终会到达那里。
首先,命令和连接是一次性资源,因此在完成它们时应确保它们是Disposed。一种常见的方法是在using
块中实例化它们,如下所示。
其次,您应该始终使用参数化查询,而不是将字符串连接在一起。我不知道ClientID
是字符串还是数字,您似乎都是双向使用它,但如果有人在文本框中键入' OR 1=1; --
而组合框在索引1上,那么您最终可能会删除所有内容。
最后,你有很多重复。根据我的假设,您可以将代码清理为:
private void btnDelete_Click(object sender, EventArgs e)
{
string query = "DELETE FROM Clients WHERE ClientID = @ClientID";
using (OleDbConnection myDb = new OleDbConnection(connectionString + DBFile))
using (OleDbCommand command = myDb.CreateCommand())
{
int clientid = 0;
command.CommandText = query;
OleDbParameter parClientID = new OleDbParameter("@ClientID", OleDbType.Integer);
command.Parameters.Add(parClientID);
myDb.Open();
foreach (DataGridViewRow myRow in dataGridView1.SelectedRows)
{
//Assume your client id is in a cell of the row? Zero for first, One for second, etc.
if (int.TryParse(myRow.Cells[0].ToString(), out clientid))
{
parClientID.Value = clientid;
command.ExecuteNonQuery();
}
}
}
}