Habeeb
Habeeb

Reputation: 8007

Backup MySQL Database using C#

Is it possible to periodically backup my MySQL Database from my application (C#). I will create the application as a Windows Service or Console app and schedule using Windows Task Scheduler.

Upvotes: 0

Views: 769

Answers (1)

Habeeb
Habeeb

Reputation: 8007

There is an awesome Library available to Backup and Restore MySQL database in C#.

The code is available on GitHub and can also be added as a Nuget package as well.

Use the below code to do a backup.

string connstr = "server=localhost;user=root;pwd=mypass;database=mydb;sslmode=none;convertdatetime=true;";
string backupfile = "C:\\backup.sql";

using (MySqlConnection conn = new MySqlConnection(connstr))
{
    using (MySqlCommand cmd = new MySqlCommand())
    {
        using (MySqlBackup mb = new MySqlBackup(cmd))
        {
            conn.Open();
            cmd.Connection = conn;

            mb.ExportToFile(backupfile);

            conn.Close();
        }
    }
}

Backup will be saved in C:\backup.sql

Upvotes: 2

Related Questions