【问题标题】:Removing Rows from Database in C# with MYSQL在 C# 中使用 MYSQL 从数据库中删除行
【发布时间】:2016-12-08 01:50:16
【问题描述】:

这是我第一次来这里,如果我错过了发布规则或其他任何内容,请多多包涵。 我正在寻找使用 C# 从数据库中删除一行的正确方法。我已经编写了从 datagridview 中删除它的代码,但是我要添加什么来完全从数据库中删除它?

这是目前为止的代码:

foreach (DataGridViewRow row in dataGridView1.SelectedRows)
{
   if (!row.IsNewRow)
   {
      dataGridView1.Rows.Remove(row);
   }

   MessageBox.Show("Selected rows Deleted");
}

这是我一开始尝试的,认为可以通过搜索:

OpenConnection();
string productType = txtDeleteProduct.Text;
MainForm frm = new MainForm();
mySqlDataAdapter = new MySqlDataAdapter("DELETE * from products        WHERE ProductType= '@productType';", connection);
DataSet DS = new DataSet();
mySqlDataAdapter.Fill(DS);
dataGridView1.DataSource = DS.Tables[0];
CloseConnection();

【问题讨论】:

  • AFAIK DataGridView.Rows.Remove 只是从数据集中删除项目,而不是从数据库中删除。您需要包含 SQL 命令来删除选定的行并使用ExecuteNonQuery 方法来运行它。
  • 您需要使用MySQLCommandBuilder。这是关于 MySQLCommandBuilder 的SO question。也许它可以帮助你。

标签: c# mysql database


【解决方案1】:

这是对您的第二个示例的改编:

using (var cn = new MySqlDbConnection("your connection string here"))
using (var cmd = new MySqlDbCommand("DELETE * from products WHERE ProductType= @productType;")) // Note that I removed the single quotes (')
{
    //Use the actual column type and length here.
    // Ignore examples elsewhere online that use AddWithValue(). This is better!
    cmd.Parameters.Add("@productType", MySqlDbType.VarString, 25).Value = txtDeleteProduct.Text;
    cn.Open();
    cmd.ExecuteNonQuery();
}

你的问题中没有足够的信息让我完全完成这个。您需要类似的东西,但在 SQL 语句中使用您的实际表名和关键字段。这里有一些更接近的东西:

using (var cn = new MySqlDbConnection("your connection string here"))
using (var cmd = new MySqlDbCommand("DELETE * from `MYTABLE` WHERE MyIDColumn = @rowKey;")) // Note that I removed the single quotes (')
{
    cmd.Parameters.Add("@rowKey", MySqlDbType.Int32);
    cn.Open();

    foreach (DataGridViewRow row in dataGridView1.SelectedRows)
    {
        if (!row.IsNewRow)
        {
            //not sure which cell(s) in the grid make up your primary key
            cmd.Parameters["@rowKey"].Value = Convert.ToInt32(row.Cells[0]);
            cmd.ExecuteNonQuery();
            dataGridView1.Rows.Remove(row);
        }        
    }    
}
MessageBox.Show("Selected rows Deleted");

最后...这里的正常程序实际上是发送删除命令,然后重新绑定网格...从头开始重新加载所有内容。您这样做是因为您已经有代码来加载网格,因此它可以为您节省一些编码工作,并且因为它让您有机会在同时表中的其他内容发生更改时更新内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-20
    • 1970-01-01
    • 1970-01-01
    • 2016-02-27
    • 1970-01-01
    相关资源
    最近更新 更多