【C#】C#备份SqlServer数据库

方法

/// <summary>
/// 数据库备份
/// </summary>
/// <param name="pathFolder">备份文件夹</param>
/// <param name="databaseName">备份数据库</param>
/// <returns></returns>
public bool Backup(string pathFolder, string databaseName)
{
    try
    {
        //创建ServerConnection的实例
        ServerConnection connection = new ServerConnection();
        //指定连接字符串 
        connection.ConnectionString = "server=WZWANG-PC;database=" + databaseName + ";uid=sa;pwd=123";
        //实例化Server 
        Server server = new Server(connection);

        //备份文件名称
        string backFileName = databaseName + DateTime.Now.ToString("yyyyMMddHHmmss");

        //创建备份设备 
        BackupDeviceItem bkDeviceItem = new BackupDeviceItem();
        bkDeviceItem.DeviceType = DeviceType.File;
        //备份完整路径
        bkDeviceItem.Name = pathFolder + "\\" + backFileName + ".bak";

        //创建数据库备份对象
        Backup backup = new Backup();
        backup.Action = BackupActionType.Database;//完全备份 
        backup.Database = connection.SqlConnectionObject.Database;//数据库名
        backup.BackupSetDescription = "完整备份";
        backup.BackupSetName = databaseName + "(通过软件备份)";
        backup.Devices.Add(bkDeviceItem);
        backup.Incremental = false;
        backup.LogTruncation = BackupTruncateLogType.Truncate;
        backup.PercentCompleteNotification = 10;
        //备份完成时执行操作
        backup.Complete += (s, e) => { };
        //备份
        backup.SqlBackup(server);

        return true;
    }
    catch { }

    return false;
}

使用

Backup(@"G:\Database\", "School");

 

也可以直接通过sql语句备份

用sql语句备份数据库 backup database

 

相关推荐
©️2020 CSDN 皮肤主题: 精致技术 设计师:CSDN官方博客 返回首页