Skip to main content

Do more object declarations affect the program?

I am programming in Windows Form and MySQL.

If I declare

 MySqlConnection connection = null;
 MySqlCommand command = null;
 MySqlDataReader Reader;

in the program,

I can use the connection and command objects in the whole .cs page.

But if I write the code below,

 private void cmbo_class_SelectedValueChanged(object sender, EventArgs e)
        {
            string clas = cmbo_class.SelectedItem.ToString();            

            try
            {
                MySqlConnection connection = new MySqlConnection(hp.myConnStr);
                MySqlCommand command = connection.CreateCommand();
                MySqlDataReader Reader;
                command.CommandText = "select id,code from reg_class_master where name ='" + clas + "' and Delete_Status=0";
                connection.Open();
                Reader = command.ExecuteReader();
                while (Reader.Read())
                {
                    class_id = Convert.ToInt32(Reader[0].ToString());
                    class_code = Reader[1].ToString();
                }
                connection.Close();
            }
            catch(Exception ex)
            {
                MessageBox.Show("Error in ","Information",MessageBoxButtons.OK,MessageBoxIcon.Information);
            }

            cmbo_division.Items.Clear();
            
            try
            {
                MySqlConnection connection = new MySqlConnection(hp.myConnStr);
                MySqlCommand command = connection.CreateCommand();
                MySqlDataReader Reader;
                command.CommandText = "select name from reg_division_master where class_id = " + class_id + " and Delete_Status=0 order by display_index";
                connection.Open();
                Reader = command.ExecuteReader();
                while (Reader.Read())
                {
                    cmbo_division.Items.Add(Reader[0].ToString());
                }
                connection.Close();
            }
            catch
            {
            }

connection and command objects are declared twice. I think one object declaration is the best way. Do more object declarations affect the program?

Sagotharan
  • 205
  • 1
  • 4
  • 12