问题
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.
回答1:
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.
回答2:
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:
- Making Your Own MySQL Backup and Restore Tools in C# (Supports Unicode, UTF8)
- CodePlex Repository
(It's not as fast or reliable as using mysqldump.exe / mysql.exe, but you can learn a lot from it.)
回答3:
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();
}
}
}
回答4:
You could try http://www.devart.com/dotconnect/mysql/docs/Devart.Data.MySql~Devart.Data.MySql.MySqlDump.html
来源:https://stackoverflow.com/questions/4233988/back-up-and-restore-mysql-database-c-sharp