简体   繁体   中英

can't manually update a mysql database containing text fields with c#

I'm struggling with the problem of updating a MySQL database using a Windows Forms app. The code looks like this:

global_data.MyDA.UpdateCommand = new MySqlCommand("UPDATE words SET word = @word WHERE id = @id", global_data.connection);
global_data.MyDA.UpdateCommand.Parameters.Add(
    new MySqlParameter("@word", MySqlDbType.Text, 0x7FFF, ParameterDirection.Input, false,
    0, 0, "word", DataRowVersion.Proposed, (object)edtWord.Text));
global_data.MyDA.UpdateCommand.Parameters.Add(
    new MySqlParameter("@id", MySqlDbType.UInt32, 10, ParameterDirection.Input, false,
    0, 0, "id", DataRowVersion.Proposed, (object)current_id)); 
global_data.MyDA.Update(table);

However, it fails to update anything (in this case - replacing a string value with edtWord.Text ).
Could anyone help? Thanks!

Seems that you are trying to update the backend database with changes in the table object. That's fine for the Update method of a DataAdapter and when the table is binded to some UI control (a DataGridView for example) that changes its underlying datasource.

But if you have a simple unbound textbox and you want to update a record in the database the correct approach is to define a command and execute it

string cmdText = "UPDATE words SET word = @word WHERE id = @id";
using(MySqlConnection cn = new MySqlConnection(constring))
using(MySqlCommand cmd = new MySqlCommand(cmdText, cn))
{
    cn.Open();
    cmd.Parameters.AddWithValue("@word", edtWord.Text);
    cmd.Parameters.AddWithValue("@id", current_id);
    cmd.ExecuteNonQuery();
}

Note I have simplified the Parameter syntax for the sake of readability, not to imply that your code is wrong

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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