-2

im trying to back up my database with the code below using mysqlBackUp 2.0.4

private void button9_Click_1(object sender, EventArgs e)
        {
            try
            {
                string constring = "Data Source=localhost;User Id=root;Password=sulyman;database=accounting_db";
                MySqlConnection conn = new MySqlConnection(constring);
                string file = "D:\\backup.sql";
                cmd = new MySqlCommand();
                cmd.Connection = conn;
                dal.Open();
                MySqlBackup ba = new MySqlBackup(cmd);
                ba.ExportToFile(file);
                dal.close();
                MessageBox.Show("done");
            }
            catch(Exception ex)
            { MessageBox.Show(ex.Message); }


        }

but i got the error

a object reference note set to an instance of an object

at the line

 ba.ExportToFile(file);

where is the wrong with my code please

Sulyman
  • 440
  • 5
  • 14

1 Answers1

1

Problem: Seems like DB connection is not open or you are using dal.Open() instead of conn.Open().

  1. I have commented dal.Open();, dal.Close(); and added conn.Open();
  2. Delcared MySqlCommand inside method.
  3. Added using statement

Try this code:

private void button9_Click_1(object sender, EventArgs e)
    {
        try
        {
            string constring = "Data Source=localhost;User Id=root;Password=sulyman;database=accounting_db";
            string file = "D:\\backup.sql";
            using(MySqlConnection conn = new MySqlConnection(constring))                
            using(MySqlCommand cmd = new MySqlCommand())
            {
                cmd.Connection = conn;
                conn.Open(); //dal.Open();
                using(MySqlBackup ba = new MySqlBackup(cmd))
                {
                   ba.ExportToFile(file);
                   //dal.close();
                   MessageBox.Show("done");
                }
            }

        catch(Exception ex)
        { MessageBox.Show(ex.Message); }

    }
Hassan
  • 5,360
  • 2
  • 22
  • 35
  • 1
    yes that is right.i corrected it while u r writing the solution dal is my connection class and i used to use it to open and close the connection but here im using defferent connection thanks very much Hassan Nisar – Sulyman Sep 01 '14 at 01:37