Night Walker
Night Walker

Reputation: 21270

back up and restore mysql database c#

I am looking for a way how I can via c# back up some database from mysql (file backup). And also via c# restore database from backup file to some new location.

Can you help me with some ideas how to get started here .

Thanks.

Upvotes: 2

Views: 10442

Answers (4)

mjb
mjb

Reputation: 7969

As alternative to MySqlDump, you can try MySqlBackup.NET: https://github.com/MySqlBackupNET/MySqlBackup.Net

Example

Backup/Export a MySQL Database

string constring = "server=localhost;user=root;pwd=qwerty;database=test;";

// Important Additional Connection Options
constring += "charset=utf8;convertzerodatetime=true;";

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

Import/Restore a MySQL Database

string constring = "server=localhost;user=root;pwd=qwerty;database=test;";

// Important Additional Connection Options
constring += "charset=utf8;convertzerodatetime=true;";

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

Upvotes: 3

JohnB
JohnB

Reputation: 18982

The CodeProject you found does backups by calling mysqldump.exe and does restores by calling mysql.exe from within a C# program (as Marc B recommended).

As an alternative, this CodeProject actually generates the SQL statements itself instead of calling an external program:

(It's not as fast or reliable as using mysqldump.exe / mysql.exe, but you can learn a lot from it.)

Upvotes: 2

swedishhousemafia
swedishhousemafia

Reputation: 129

ProcessStartInfo startInfo = new ProcessStartInfo("cmd.exe");
Process.Start(startInfo);
startInfo.Arguments = "mysqldump -u admin -p admin test > c:\backupfile.sql";
Process.Start(startInfo);

You can hide the dos prompt with startInfo.WindowStyle if you need.

Upvotes: 4

Related Questions