基本功能:
1:异步备份MySql数据库
2:如果备份成功,有耗时提示,并提供备份文件下载;如果备份失败,则提示错误信息。
设计页面截图:
数据库备份的核心代码:
string strConn = "server=localhost;database=AgrBankBox3;uid=root;pwd=888888;charset=gb2312;";
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DeleteOldFile();
try
{
lblMsg.Text = "";
if (!TestConnection())
{
return;
}
BackupData();
}
catch (Exception ex)
{
lblMsg.Text = ex.Message;
}
}
}
void mb_ProgressCompleted(object sender, MySqlBackupCompleteArg e)
{
if (e.CompletedType == MySqlBackupCompleteArg.CompleteType.Error)
{
Response.Write(e.ExceptionInfo.ToString());
}
else
{
Session["resultmsg"] = "耗时: " + e.TimeUsed.Hours + " 时 " + e.TimeUsed.Minutes + " 分 " + e.TimeUsed.Seconds + " 秒 " + e.TimeUsed.Milliseconds + " 毫秒.";
Response.Redirect("BackupComplete.aspx");
}
}
void DeleteOldFile()
{
string timeNow = DateTime.Now.AddMinutes(-15).ToString("yyyyMMddHHmmss");
long iTimeNow = Convert.ToInt64(timeNow);
string[] oldFiles = System.IO.Directory.GetFiles(Server.MapPath("~/dumpfiles"));
foreach (string s in oldFiles)
{
if (!s.EndsWith("sql"))
{
continue;
}
long fileTime = Convert.ToInt64(System.IO.Path.GetFileNameWithoutExtension(s));
if (fileTime < iTimeNow)
{
try
{
System.IO.File.Delete(s);
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
}
}
bool TestConnection()
{
try
{
MySqlConnection conn = new MySqlConnection(strConn);
conn.Open();
conn.Close();
return true;
}
catch (Exception ex)
{
lblMsg.Text = ex.Message;
return false;
}
}
private void BackupData()
{
try
{
string[] tables = new string[] { };
DataTable dt = new DataTable();
MySqlBackup mb = new MySqlBackup(strConn);
dt.Columns.Add("columns");
tables = mb.DatabaseInfo.AllTableNames;
foreach (string s in tables)
{
dt.Rows.Add(s);
}
if (tables != null)
{
mb.TablesToBeExported = tables;
}
mb.AddCreateDatabase = true;
mb.EnableEncryption = false;
mb.ExportRows = true;
mb.ExportTableStructure = true;
mb.ResetAutoIncrement = false;
mb.ExportFunctions = true;
mb.ExportStoredProcedures = true;
mb.ExportEvents = true;
mb.ExportViews = true;
mb.ExportTriggers = true;
mb.ProgressCompleted += new MySqlBackup.progressComplete(mb_ProgressCompleted);
//mb.EncryptionKey = settings[10];
mb.Export(Session["dumpfile"].ToString());
}
catch (Exception ex)
{
Session["errmsg"] = ex.ToString();
}