码迷,mamicode.com
首页 > 数据库 > 详细

SQL备份数据库代码

时间:2016-05-02 14:12:48      阅读:295      评论:0      收藏:0      [点我收藏+]

标签:

SQL备份数据库代码

#region 服务每天备份一次数据库
/// <summary>
/// 服务每天备份一次数据库
/// </summary>
public void ServiceForBackupDatabaseEveryDay()
{
    Thread thread = new Thread(new ThreadStart(BackupDatabaseEveryDay));
    thread.IsBackground = true;
    thread.Start();
}

private void BackupDatabaseEveryDay()
{
    while (true)
    {
        try
        {
            //每天凌晨1点进行全备份
            if (DateTime.Now.Hour == 1)
            {
                string filename = string.Format("Grandmap.Cms_Full_{0}.bak", DateTime.Now.ToString("yyyyMMddHHmmss"));
                Hashtable param = new Hashtable();
                param.Add("DatabaseName", "Grandmap.Cms");
                param.Add("FileName", filename);

                //<![CDATA[ BACKUP DATABASE $DatabaseName$ TO DISK = ‘$FileName$‘;]]>
            }

            Thread.Sleep(TimeSpan.FromHours(1));
        }
        catch (Exception ex)
        {
            Log4Net.Error("每天凌晨1点进行全备份数据库服务异常!", ex);
        }
    }
}
#endregion

#region 每天12点和18点进行一次差异备份
/// <summary>
/// 每天12点和18点进行一次差异备份
/// </summary>
public void ServiceForBackupDatabaseWithDiffrent()
{
    Thread thread = new Thread(new ThreadStart(BackupDatabaseWithDiffrent));
    thread.IsBackground = true;
    thread.Start();
}

private void BackupDatabaseWithDiffrent()
{
    while (true)
    {
        try
        {
            //每天12点和18进行差异备份
            if (DateTime.Now.Hour == 12 || DateTime.Now.Hour == 18)
            {
                string filename = string.Format("Grandmap.Cms_Diffrent_{0}.bak", DateTime.Now.ToString("yyyyMMddHHmmss"));
                Hashtable param = new Hashtable();
                param.Add("DatabaseName", "Grandmap.Cms");
                param.Add("FileName", filename);

                //<![CDATA[ BACKUP DATABASE $DatabaseName$ TO DISK = ‘$FileName$‘ WITH DIFFERENTIAL;]]>
            }

            Thread.Sleep(TimeSpan.FromHours(1));
        }
        catch (Exception ex)
        {
            Log4Net.Error("每天12点和18进行差异备份数据库服务异常!", ex);
        }
    }
}
#endregion

#region 文件夹创建
/// <summary>
/// 文件夹创建
/// </summary>
public void CreateDir()
{
    string filedir = DateTime.Now.ToString("yyyy-MM");
    string xmlPath = AppDomain.CurrentDomain.BaseDirectory;
    xmlPath = System.IO.Path.GetDirectoryName(xmlPath);

    if (!xmlPath.EndsWith("\\"))
    {
        xmlPath += "\\";
    }

    xmlPath = string.Format("{0}DatabaseDir\\{1}", xmlPath, filedir);

    if (!Directory.Exists(xmlPath))
    {
        Directory.CreateDirectory(xmlPath);
    }
}
#endregion

 

SQL备份数据库代码

标签:

原文地址:http://www.cnblogs.com/hunttown/p/5452279.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!