简体   繁体   中英

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. Please advice, I am a beginner in 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. if the Key is duplicate(existing) the the value get updated. 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);

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