使用Mysqlbackup 2.0.4时出现Mysqlbackup错误

本文关键字:Mysqlbackup 错误 使用 4时 | 更新日期: 2023-09-27 18:20:06

im试图使用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);

我的代码哪里有问题,请

使用Mysqlbackup 2.0.4时出现Mysqlbackup错误

问题:似乎DB连接未打开,或者您使用的是dal.Open()而不是conn.Open()

  1. 我已经评论了dal.Open();dal.Close();并添加了conn.Open();
  2. Delcare MySqlCommand内部方法
  3. 添加using语句

试试这个代码:

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