使用 C# 在 MySQL 中备份数据库

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12311492/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 22:49:42  来源:igfitidea点击:

Backing up Database in MySQL using C#

c#mysqlwinforms

提问by Bon

I created a Winforms in order to backup my Database. Then When I run my program it gives an Win32Exception was unhandled. "The system cannot find the file specified" Although the file is already existed and resulted to that exception.

我创建了一个 Winforms 来备份我的数据库。然后当我运行我的程序时,它给出了一个未处理的 Win32Exception。“系统找不到指定的文件”尽管该文件已存在并导致该异常。

Here is my code regarding my problem

这是我关于我的问题的代码

using System.Diagnostics;

private void btnProceed_Click(object sender, EventArgs e)
{
            path = @"D:\MySQL\MySQL Server 5.5\bin\mysqldump.exe -u " + txtBoxDBUsername.Text + @" -p " + txtBoxDBName.Text + @" > D:\C#\Client\Salesmate - EMC\SalesMate\Backup\" + maskeTxtBoxDBFile.Text + @"";
            Process p = new Process();
            p.StartInfo.FileName = path;
            p.Start();
}

采纳答案by mjb

You can use MySqlBackup.NETas alternative to MySqlDump
Documentation:
http://www.codeproject.com/Articles/256466/MySqlBackup-NET-MySQL-Backup-Solution-for-Csharp-V
https://github.com/MySqlBackupNET/MySqlBackup.Net

Sample codes:

Backup a MySQL database

您可以使用MySqlBackup.NET作为MySqlDump
文档的替代:
http: //www.codeproject.com/Articles/256466/MySqlBackup-NET-MySQL-Backup-Solution-for-Csharp-V
https://github.com/MySqlBackupNET /MySqlBackup.Net

示例代码:

备份 MySQL 数据库

using MySql.Data.MySqlClient; 

then the code,

然后是代码

private void Backup()
{
    string constring = "server=localhost;user=root;pwd=qwerty;database=test;";
    string file = "C:\backup.sql";
    using (MySqlConnection conn = new MySqlConnection(constring))
    {
        using (MySqlCommand cmd = new MySqlCommand())
        {
            using (MySqlBackup mb = new MySqlBackup(cmd))
            {
                cmd.Connection = conn;
                conn.Open();
                mb.ExportToFile(file);
                conn.Close();
            }
        }
    }
}


Restore a MySQL database


还原 MySQL 数据库

private void Restore()
{
    string constring = "server=localhost;user=root;pwd=qwerty;database=test;";
    string file = "C:\backup.sql";
    using (MySqlConnection conn = new MySqlConnection(constring))
    {
        using (MySqlCommand cmd = new MySqlCommand())
        {
            using (MySqlBackup mb = new MySqlBackup(cmd))
            {
                cmd.Connection = conn;
                conn.Open();
                mb.ImportFromFile(file);
                conn.Close();
            }
        }
    }
}

Update:
I am one of the author of this library.

更新:
我是这个库的作者之一。

回答by hagensoft

I believe you have to mention the user, pwd, db name and the target path..

我相信您必须提到用户,密码,数据库名称和目标路径..

string path = @"C:\Program Files\MySQL\MySQL Server 5.5\bin\mysqldump.exe -u " + txtBoxDBUsername.Text + @" -p " + txtBoxDBName.Text + @" > " + txtBoxDBName.Text + @".sql"; 

backup: # mysqldump -u root -p[root_password] [database_name] > dumpfilename.sql

备份:#mysqldump -u root -p[root_password] [database_name] > dumpfilename.sql

restore:# mysql -u root -p[root_password] [database_name] < dumpfilename.sql

恢复:# mysql -u root -p[root_password] [database_name] < dumpfilename.sql

http://www.thegeekstuff.com/2008/09/backup-and-restore-mysql-database-using-mysqldump/

http://www.thegeekstuff.com/2008/09/backup-and-restore-mysql-database-using-mysqldump/

回答by jekol

I have try that code but problem is occure in before run. exeption is -An unhandled exception of type 'System.IO.FileLoadException' occurred in System.Windows.Forms.dll

我已经尝试过该代码,但在运行之前出现了问题。例外是 - System.Windows.Forms.dll 中发生类型为“System.IO.FileLoadException”的未处理异常

Additional information: Could not load file or assembly 'MySql.Data, Version=6.5.4.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

附加信息:无法加载文件或程序集“MySql.Data, Version=6.5.4.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d”或其依赖项之一。定位的程序集的清单定义与程序集引用不匹配。(来自 HRESULT 的异常:0x80131040)

回答by Ramgy Borja

You may try this one.

你可以试试这个。

    public void BackUpData(string file)
    {
        using (MySqlConnection con = new MySqlConnection { ConnectionString = config })
        {
            using (MySqlCommand cmd = new MySqlCommand { Connection = con })
            {
                using (MySqlBackup mb = new MySqlBackup { Command = cmd })
                {


                    try
                    {
                        con.Open();

                        try
                        {
                            mb.ExportToFile(file);
                        }
                        catch(MySqlException ex)
                        {
                            msgErr(ex.Message + " sql query error.");
                            return;
                        }
                    }
                    catch(MySqlException ex)
                    {
                        msgErr(ex.Message + " connection error.");
                        return;
                    }



                }

            }

        }

    }

回答by tedebus

  • Don't putt the whole call inside "path = ", you should use "Arguments" to specify arguments, as name says. If library checks for presence of the called file (your whole path) it shouldn't find it!
  • Are you sure that path is correct? You should find MySQL Server path using registry, not hard-coding the path, or if it can be not easy for you you can pass it as an argument from command line or specify from your form (settings page).
  • You may have missed credentials: -u should be used for username (even if I use --user) and -p should be for password (even if I use --password). Why do you pass "txtBoxDBName.Text" as password?!
  • Maybe your destination path is invalid: it contains spaces, if you use spaces you should use quotes.
  • What does txtBoxDBName.Text (?password?) contains? Spaces too? If yes it doesn't work.
  • Last presence of + @""is completely useless, it doesn't insert any quotes.
  • 不要把整个调用放在“path =”中,你应该使用“Arguments”来指定参数,正如名称所说。如果库检查被调用文件(您的整个路径)的存在,它不应该找到它!
  • 你确定这条路是正确的吗?您应该使用注册表找到 MySQL 服务器路径,而不是对路径进行硬编码,或者如果对您来说不容易,您可以将它作为参数从命令行传递或从您的表单(设置页面)中指定。
  • 您可能遗漏了凭据:-u 应该用于用户名(即使我使用 --user),-p 应该用于密码(即使我使用 --password)。为什么要传递“txtBoxDB Name.Text”作为密码?!
  • 也许您的目标路径无效:它包含空格,如果您使用空格,则应使用引号。
  • txtBoxDBName.Text (?password?) 包含什么?还有空格?如果是,它不起作用。
  • 最后的存在 + @""完全没用,它不插入任何引号。

A correct version of your code with quotes corrected is: path = @"""D:\MySQL\MySQL Server 5.5\bin\mysqldump.exe"" -u " + txtBoxDBUsername.Text + @" -p " + txtBoxDBName.Text + @" > ""D:\C#\Client\Salesmate - EMC\SalesMate\Backup\" + maskeTxtBoxDBFile.Text + @"""";

更正引号的正确代码版本是: path = @"""D:\MySQL\MySQL Server 5.5\bin\mysqldump.exe"" -u " + txtBoxDBUsername.Text + @" -p " + txtBoxDBName.Text + @" > ""D:\C#\Client\Salesmate - EMC\SalesMate\Backup\" + maskeTxtBoxDBFile.Text + @"""";

For more readability: path = $@"""D:\MySQL\MySQL Server 5.5\bin\mysqldump.exe"" -u {txtBoxDBUsername.Text} -p {txtBoxDBName.Text} > ""D:\C#\Client\Salesmate - EMC\SalesMate\Backup{maskeTxtBoxDBFile.Text}""";

为了提高可读性: path = $@"""D:\MySQL\MySQL Server 5.5\bin\mysqldump.exe"" -u {txtBoxDBUsername.Text} -p {txtBoxDBName.Text} > ""D:\C#\Client\Salesmate - EMC\SalesMate\Backup{maskeTxtBoxDBFile.Text}""";

回答by Mwenda Sam

ProcessStartInfo psi = new ProcessStartInfo();
psi.FileName = @"C:\xampp\mysql\bin\mysql.exe";
psi.RedirectStandardInput = true;
psi.RedirectStandardOutput = false;
psi.CreateNoWindow = true;
psi.Arguments = string.Format(@"-u{0} -p{1} -h{2} {3}<{4}", "root", "password", "localhost", "your_dbname", "your_.sql_file");
psi.UseShellExecute = false;
Process process = Process.Start(psi);
process.StandardInput.WriteLine(input);
process.StandardInput.Close();
process.WaitForExit();
process.Close();

This one worked for me you can try it out as long as you've your backed up .sql file

这个对我有用,只要您备份了 .sql 文件就可以尝试一下