Hello, I need to trigger an insert statement into my SQL database every time certain buttons are pressed.

There are a total of 6 buttons, which makes having:

string connString

MySqlConnection conn = new MySqlConnection(connString);

MySqlCommand command = conn.CreateCommand();

etc, etc. 6 times over in each button seem very inefficient having to repeat code numerous times.

I was wondering if someone could recommend a better way to achieve this?

Thanks.

As good practise you should have a class seperate from your interface methods (i.e. button clicks) so that they aren't as accessible and to organise your application better. Simply make another class with the connection and insert command in and simply call that from the button click events.

Would it be possible to do something along these lines?

class Program
{
  button_1_click
  {
    SQL sql = new SQL()

    sql.Connect()
    sql.Insert()
    sql.CloseConn()
  }
  button_2_click
  {
    SQL sql = new SQL()

    sql.Connect()
    sql.Insert()
    sql.CloseConn()
  }
}


class SQL
{
   void Connect()
   {
     //connect to database
   }
   void Insert()
   {
     //perform insert
   }
}

Or is there a better way to do it?

Yeah just like that but you only really need to define "SQL sql;" once at the top and then just do the "sql = new SQL();" as the first line of each method (it's not essential but it's good practise to re-use variables in this way).

Thank you very much for your help.

If you to cut down the amount of code in your project only call the insert method from the button events and the call the connect method at the start of the insert method and the close method at the end of the insert method. It only saves a couple of lines but it makes the code tidier, more readable and efficient.

Also mark this solved if i've managed to solve it for you.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.