C# Backup and Restore MySQL Database(s)

| | | |

Must Download DLLs from http://mysqlbackupnet.codeplex.com/

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;

namespace MySQLBackupRestore
	{
	public partial class Form1 : Form
		{
		public static string sMySQLServer = "192.168.43.1";
		public static string sMySQLUser = "root";
		public static string sMySQLPassword = "";

		public Form1 ()
			{
			InitializeComponent();
			}

		private void btnRestore_Click (object sender, EventArgs e)
			{

			}

		private void btnBackup_Click (object sender, EventArgs e)
			{
			Backup("mysql", "C:tempbackup.sql");
			}

		private void Backup (string sMySQLDatabase, string sFilePath)
			{
			string constring = "server=" + sMySQLServer + ";user=" + sMySQLUser + ";pwd=" + sMySQLPassword + ";database=" + sMySQLDatabase + ";";
			//string file = "C:tempbackup.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(sFilePath);
						conn.Close();
						}
					}
				}
			}

		private void Restore (string sMySQLDatabase, string sFilePath)
			{
			string constring = "server=" + sMySQLServer + ";user=" + sMySQLUser + ";pwd=" + sMySQLPassword + ";database=" + sMySQLDatabase + ";";
			//string file = "C:tempbackup.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(sFilePath);
						conn.Close();
						}
					}
				}
			}
		}
	}
Originally Posted on April 6, 2014
Last Updated on October 26, 2015
All information on this site is shared with the intention to help. Before any source code or program is ran on a production (non-development) system it is suggested you test it and fully understand what it is doing not just what it appears it is doing. I accept no responsibility for any damage you may do with this code.