如何从C#texbox更新mysql中的数据

时间:2018-01-09 02:54:34

标签: c# mysql wpf

我正试图以这种方式更新mysql数据库中的数据:

private void executeQuery(string insertQuery)
            {
                MySqlCommand dataCommand = new MySqlCommand();
                using (MySqlConnection dataConnection = new MySqlConnection())
                try
                    {
                        dataConnection.ConnectionString = @"server=localhost;user id=root; password=root; database=pop-sf40-database";
                        dataConnection.Open();
                        dataCommand = new MySqlCommand(insertQuery, dataConnection);
                        if (dataCommand.ExecuteNonQuery() == 1)
                        {
                            MessageBox.Show("Done.");
                        }
                        else
                        {
                            MessageBox.Show("Error.");
                        }
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message);
                    }
                    finally
                    {
                        dataConnection.Close();
                    }
            }

        private void btnUpdate_Click(object sender, RoutedEventArgs e)
        {
            using (MySqlConnection dataConnection = new MySqlConnection())
                try
                {
                    dataConnection.ConnectionString = @"server=localhost;user id=root; password=root; database=pop-sf40-database";
                    dataConnection.Open();
                    string updateQuery = "UPDATE `pop-sf40-database`.`salons` SET `id` = '"+ txtSalonId.Text + "', `name` = '" + txtSalonName.Text + "', `adress` = '" + txtSalonAdress.Text + "', `telephone` = '" + txtSalonTelephone.Text + "', `email` = '" + txtSalonEmail.Text + "', `web_site` = '" + txtSalonSite.Text + "', `tin` = '" + txtSalonTin.Text + "', `uid` = '" + txtSalonUid.Text + "', `bank_account` = '" + txtSalonBankAccount.Text + "', `deleted` = '" + 0 + "'";
                    executeQuery(updateQuery);
                }
                catch (MySqlException ex)
                {
                    MessageBox.Show(ex.ToString());
                }
                finally
                {
                    dataConnection.Close();
                }
            txtSalonId.Clear();
            txtSalonName.Clear();
            txtSalonAdress.Clear();
            txtSalonTelephone.Clear();
            txtSalonEmail.Clear();
            txtSalonBankAccount.Clear();
            txtSalonSite.Clear();
            txtSalonTin.Clear();
            txtSalonUid.Clear();
            txtSalonBankAccount.Clear();
        }

但是,在数据库中,Id必须是唯一的,当然。问题是:enter image description here

例如,如果我在文本框中显示所有沙龙数据并仅更改地址,则仍会为ID,主键抛出ecxception。

1 个答案:

答案 0 :(得分:0)

您正在尝试更新更新SQL中的id,并且缺少where子句,因此实际上您要将salons表中的所有记录更新为相同的{ {1}}(在您的情况下为2),这就是显示错误

的原因

您应该使用更新SQL的id子句中的id,例如:

where