-1

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.

stckf
  • 3
  • 1
  • possible duplicate of [How to directly execute SQL query in C#? Have example batch file](http://stackoverflow.com/questions/21709305/how-to-directly-execute-sql-query-in-c-have-example-batch-file) – Mihai Caracostea Sep 05 '15 at 07:05

1 Answers1

0

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);
sujith karivelil
  • 28,671
  • 6
  • 55
  • 88