简体   繁体   中英

How to update MySql table row through C# console application?

I am writing a console application and fetch data from MySql table . Code :

 string connection = "Server=localhoht;Database=data;Uid=root;Pwd=root123";
        MySqlConnection dbcon = new MySqlConnection(connection);
        MySqlCommand selectData;
        dbcon.Open();
        selectData = dbcon.CreateCommand();
selectData.CommandText = "SELECT user_id, user_name,user_type FROM win_user WHERE user_type=1 ORDER BY user_id ASC ";
        MySqlDataReader juh = selectData.ExecuteReader();

And its working fine. Now I want to update a row with the code below :

string updatedata = "UPDATE win_user SET user_type='1' WHERE user_id= '1'";
        MySqlDataAdapter MyData = new MySqlDataAdapter();
        MyData.UpdateCommand = new MySqlCommand(updatedata, dbcon);  

But its not working.

您可以在任何sql客户端工具(例如navicat)中运行命令“ UPDATE win_user SET user_type ='1'WHERE user_id ='1'”,以验证它在mysql数据库上是否正确。

The MySqlDataAdapter could be used to update rows in a database table using the Update method.
The Update method (link is for SqlServer but the concept is the same) has many overload, but basically it requires a DataTable with rows modified in some way ([RowState != DataRowState.Unchanged][2]) so the MySqlDataAdapter can pick the rows changed and apply the DeleteCommand , UpdateCommand and InsertCommand defined in the adapter

Your code above doesn't shown any kind of interaction with a datatable and you have a call to the Update method so there is no way for the update to occur.

You could, of course execute directly your command without any adapter involved

EDITed to change every user_type not 1 to 1

string updatedata = "UPDATE win_user SET user_type=1 WHERE user_type <> 1";
MySqlCommand cmd = new MySqlCommand(updatedata, dbcon);  
int numOfRowsChanged = cmd.ExecuteNonQuery();

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