删除按钮SQL数据库Windows窗体应用程序

本文关键字:窗体 应用程序 Windows 数据库 按钮 SQL 删除 | 更新日期: 2023-09-27 17:52:55

我如何修改我的删除按钮代码从我的SQL数据库中删除选定的行?目前,当我选择一行并单击删除按钮时,所有的行都被删除了。

private void delete_button1_Click_1(object sender, EventArgs e)
    {
        if (dataGridView1.SelectedRows.Count > 0)
        {
            int selectedIndex = dataGridView1.SelectedRows[0].Index;
            string sqlquery;
            string ConString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
            MySqlConnection con = new MySqlConnection(ConString);
            con.Open();
            int rowID = int.Parse(dataGridView1[0, selectedIndex].Value.ToString());
            sqlquery = "DELETE FROM hotel_booking WHERE BookingID = BookingID";
            try
            {
                MySqlCommand command = new MySqlCommand(sqlquery, con);
                command.ExecuteNonQuery();
                string CmdString = "SELECT * FROM hotel_booking";
                MySqlDataAdapter sda = new MySqlDataAdapter(CmdString, con);
                DataSet ds = new DataSet();
                sda.Fill(ds);
                dataGridView1.DataSource = ds.Tables[0].DefaultView;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
    }

删除按钮SQL数据库Windows窗体应用程序

不要尝试运行这个查询,它将删除您的所有行

DELETE FROM hotel_booking WHERE BookingID = BookingID

BookingID = BookingID意味着它总是为真

我认为你在试图使用

int rowID = int.Parse(dataGridView1[0, selectedIndex].Value.ToString());
sqlquery = "DELETE FROM hotel_booking WHERE BookingID = "+ rowID;

由于WHERE子句中的错误,您当前正在删除所有行:

DELETE FROM hotel_booking WHERE BookingID = BookingID

删除所有行,因为每一行BookingID等于BookingID

您希望将rowID作为标准,因此将其作为参数添加:

int rowID = int.Parse(dataGridView1[0, selectedIndex].Value.ToString());
sqlquery = "DELETE FROM hotel_booking WHERE BookingID = @rid";   
try
{
    MySqlCommand command = new MySqlCommand(sqlquery, con);
    command.Parameters.Add("@rid", SqlDbType.Int).Value = rowID;
    command.ExecuteNonQuery();

请注意,将用户生成的值直接插入到查询中(如"WHERE BookingID = " + rowID...)容易受到SQL注入的攻击。尽管对于数字类型来说,这不是一个很大的危险,但您通常应该像上面那样使用参数化查询。

你的问题在这里:

sqlquery = "DELETE FROM hotel_booking WHERE BookingID = BookingID"

where部分总是正确的。

改成:

sqlquery = "DELETE FROM hotel_booking WHERE BookingID = @BookingID"
try
        {
            MySqlCommand command = new MySqlCommand(sqlquery, con);
            command.Parameters.AddWithValue("@BookingID", rowID);
            command.ExecuteNonQuery();
            ...