C#mysql database backup and restore

Time:2021-9-9

1: Reference DLL

MySql.Data.dll, MySqlbackup.dll

2: Create a data connection static class

public static class mysql
{
Public static string constr = "database = test; password = password; user id = root; server = IP address";
public static MySqlConnection conn = new MySqlConnection(constr);
}

3: Create WinForm form

Backup code

DialogResult = MessageBox. Show ("the backup path is under the current program by default", "prompt", messageboxbuttons.yesno, messageboxicon. Question);
if (result == DialogResult.Yes)
{
string time1 = System.DateTime.Now.ToString("d").Replace("/", "-");
string file = ".//mysql/" + time1 + "_test.sql";
using (MySqlCommand cmd = new MySqlCommand())
{
using (MySqlBackup mb = new MySqlBackup(cmd))
{
cmd.Connection = mysql.conn;
mysql.conn.Open();
mb.ExportToFile(file);
mysql.conn.Close();
MessageBox. Show ("backed up");
}
}
}
else
{
return;
}

Restore code

string file = textBox1.Text;
if (file == "")
{
MessageBox. Show ("cannot be empty");
return;
}
DialogResult = MessageBox. Show ("are you sure to restore?", "restore", messageboxbuttons.yesno, messageboxicon. Question);
if (result == DialogResult.Yes)
{
try
{
using (MySqlCommand cmd = new MySqlCommand())
{
using (MySqlBackup mb = new MySqlBackup(cmd))
{
cmd.Connection = mysql.conn;
mysql. conn.Open();
mb.ImportFromFile(file);
mysql. conn.Close();
MessageBox. Show ("restored");
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
else
{
return;
}