ASP.NET中怎样实现数据库备份

ASP.NET中怎样实现数据库备份,第1张

static string pathBak

/// <summary>

/// 备份SQL数据库

/// </summary>

/// <param name="databasename">要备份的数据源名称</param>

/// <param name="backuptodatabase">备份到的数据库文件名称及路径.bak</param>

/// <returns>返回生成的备份文件全路径名</returns>

public string BakSql(string databaseName, string bakPath)

{

try

{

//声明临时数据库名称

string bakName = string.Empty

if (bakPath.IndexOf(".bak") <0)

{

bakName = databaseName

bakName += DateTime.Now.Year.ToString()

bakName += DateTime.Now.Month.ToString()

bakName += DateTime.Now.Day.ToString()

bakName += DateTime.Now.Hour.ToString()

bakName += DateTime.Now.Minute.ToString()

bakName += DateTime.Now.Second.ToString()

bakName += ".bak"

if (bakPath.LastIndexOf('\\') != bakPath.Length)

bakPath += '\\'

}

FileInfo fi = new FileInfo(bakPath)

if (!Directory.Exists(fi.DirectoryName))

Directory.CreateDirectory(fi.DirectoryName)

bakPath = bakPath + bakName

pathBak = bakPath

bakPath = bakPath.Replace("\\", "/")

string sqlbak = string.Format("BACKUP DATABASE " + databaseName + " TO DISK = '{0}' WITH INIT", bakPath)

if (SqlHelper.ExecuteNonQuery(Common.objCom.GetConnectionString("DBMaster"), CommandType.Text, sqlbak) != 0)

return pathBak

else

return string.Empty

}

catch (Exception ex)

{

lbTip.Text = ex.Message

lbTip.ForeColor = Color.FromName("#FF8080")

return string.Empty

}

}

备份SQL数据库:右击数据库名称,出来所有任务,选择备份数据库,选择路径就行了;

还原数据库:您先建一个sql数据录。右击数据库名称,选择所有任务,还原数据库,在选择“从设备”找到你那个备份的文件选择就好了。


欢迎分享,转载请注明来源:夏雨云

原文地址:https://www.xiayuyun.com/zonghe/58935.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-02-27
下一篇2023-02-27

发表评论

登录后才能评论

评论列表(0条)

    保存