繁体   English   中英

使用MYSQL从C#中的数据库中删除行

[英]Removing Rows from Database in C# with MYSQL

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

这是到目前为止的代码:

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();

这是第二个示例的改编:

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");

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM