使用MysqlBackup 2.0.4的Mysqlbackup错误

时间:2014-09-01 01:13:08

标签: c# mysql mysql-backup

我尝试使用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); }


        }

但是我收到了错误

a object reference note set to an instance of an object

 ba.ExportToFile(file);

我的代码在哪里错了

1 个答案:

答案 0 :(得分:1)

问题:好像数据库连接未打开或您使用的是dal.Open()而不是conn.Open()

  1. 我评论了dal.Open();dal.Close();并添加了conn.Open();
  2. 方法内的MySqlCommand
  3. 添加了using声明
  4. 试试这段代码:

    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); }
    
        }