Windows窗体应用程序更新查询未保存数据

本文关键字:保存 数据 查询 更新 窗体 应用程序 Windows | 更新日期: 2023-09-27 18:17:10

我尝试在我的c# windows窗体应用程序中使用更新查询。我没有得到任何错误,它似乎没有保存我尝试更新的数据。看看下面的代码:

private void button2_Click(object sender, EventArgs e)
{
    try
    {
        string myConnection = connection;
        MySqlConnection myConn = new MySqlConnection(myConnection);
        myConn.Open();
        MySqlDataAdapter myDataAdapter = new MySqlDataAdapter();
        myDataAdapter.UpdateCommand = new MySqlCommand(" update users set username=" + textBox1.Text + " where username=" + username + " ", myConn);
        MySqlCommandBuilder cb = new MySqlCommandBuilder(myDataAdapter);
        DataSet ds = new DataSet();
        myConn.Close();
        MessageBox.Show("Changes has been saved.");
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}
    }

用户名是来自另一个表单(gridview)的字符串。

Windows窗体应用程序更新查询未保存数据

我在网上找到了一个解决方案。我想到的是:

    private void button2_Click(object sender, EventArgs e)
    {
        string myConnection = connection;
        MySqlConnection myConn = new MySqlConnection(myConnection);
        MySqlCommand cmdDataBase = new MySqlCommand("UPDATE `users` SET username='Test' WHERE username='CurrentName' ", myConn);
        MySqlDataReader myReader;
        try
        {
            myConn.Open();
            myReader = cmdDataBase.ExecuteReader();
            myConn.Close();
            MessageBox.Show("Changes has been saved!");
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }