简体   繁体   English

简单更新 MySQL C#

[英]Simple update MySQL C#

I have simple code for insert in database and it works fine;我有简单的代码插入数据库,它工作正常;

static public void InsertUser(string userName, int age, DataGridView DadataGridView1)
    {
        try
        {
            if (connection.State == ConnectionState.Closed)
                connection.Open();
            MySqlCommand commandInsert = new MySqlCommand("INSERT INTO IP(Username,Age) VALUES(@Username,@Age)", connection);
            commandInsert.Parameters.AddWithValue("@username", userName);
            commandInsert.Parameters.AddWithValue("@age", age);
            commandInsert.ExecuteNonQuery();
            commandInsert.Parameters.Clear();
            MessageBox.Show("User Inserted sucessfuly");
        }
        catch (MySqlException exception)
        {
            MessageBox.Show(exception.ToString());

        }
        finally
        {
            connection.Close();

        }
    }

I need write code for UPDATE and GET data.我需要为 UPDATE 和 GET 数据编写代码。 Please advice, I am a beginner in C #.请指教,我是C#的初学者。 Thanks.谢谢。

Hope that you may have a primary key for this table,You can use ON DUPLICATE KEY UPDATE so that you need not to write different query for update.希望你可能有这个表的主键,你可以使用ON DUPLICATE KEY UPDATE这样你就不需要为更新编写不同的查询。 if the Key is duplicate(existing) the the value get updated.如果 Key 是重复的(现有),则该值会更新。 so your command will be like the following:所以你的命令将如下所示:

   MySqlCommand commandInsert = new MySqlCommand("INSERT INTO IP(Username,Age) VALUES(@Username,@Age) ON DUPLICATE KEY UPDATE Username=VALUES(Username),Age=VALUES(Age)", connection);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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