sqlserver 通过压缩bak文件实现从服务器还原数据库《数据差异数个小时》

news/2025/3/17 17:28:43/文章来源:https://www.cnblogs.com/chenwolong/p/18233123

十年河东,十年河西,莫欺少年穷

学无止境,精益求精

1、备份主服务器数据库并压缩

   public void DbBack(){var bakname = @"ChargeDB_" + DateTime.Now.ToString("yyyyMMdd") + ".bak";string filepath = @"D:\dbback\" + bakname;if (File.Exists(filepath)){File.Delete(filepath);}string sql = @"declare @date nvarchar(10)  
set @date = CONVERT(nvarchar(10),getdate(),112) 
declare @path nvarchar(250) 
set @path = 'D:\dbback\' 
declare @db_filename nvarchar(150)  
set @db_filename = @path + 'ChargeDB_'+@date+'.bak' 
backup database ChargeDB TO DISK=@db_filename  ";DataRepository.ExecuteCommand(sql);//压缩文件 供备份服务器下载var dbpath = @"D:\dbback\ChargeDB_" + DateTime.Now.ToString("yyyyMMdd") + ".bak";var zippath = @"D:\dbback\ChargeDB_" + DateTime.Now.ToString("yyyyMMdd") + ".zip";if (File.Exists(dbpath)){Console.WriteLine("存在数据备份文件");ZipUtility zip = new ZipUtility();zip.ZipFile(dbpath, zippath, 2, 2048);}}
View Code

2、从服务器解压缩并还原

        static void Main(string[] args){var zippath = @"C:\dbback";var zipname = @"ChargeDB_" + DateTime.Now.ToString("yyyyMMdd") + ".zip";var bakname = @"ChargeDB_" + DateTime.Now.ToString("yyyyMMdd") + ".bak";FileLoad(zipname, zippath);//
            ZipUtility zip = new ZipUtility();zip.UnZip(zippath+@"\"+ zipname, zippath);Console.WriteLine("UnZipOVER");RestoreDataBase("ChargeDB", zippath+@"\" + bakname);Console.WriteLine(" RestoreDataBaseOver");Console.Read();}/// <summary>/// 下载文件/// </summary>/// <param name="fileName">客户端保存的文件名</param>/// <param name="filePath">保存的文件夹路径</param>/// <returns></returns>public static void FileLoad(string fileName, string filePath){//判断保存的文件夹是否存在if (!Directory.Exists(filePath)){//不存在则创建
                Directory.CreateDirectory(filePath);}//System.Net 中的验证和下载方法WebClient client = new WebClient();client.Credentials = CredentialCache.DefaultCredentials;client.DownloadFile("https://chengxiangzhineng.com/dbsite/ChargeDB_20240605.zip", filePath + "\\" + fileName);Console.WriteLine("下载完成");}public static void RestoreDataBase(string dataBaseName, string dataBaseBackupFile){var CommandText = string.Format(@"USE [master]
ALTER DATABASE {0}
SET SINGLE_USER
WITH ROLLBACK IMMEDIATE;
restore database {0}  from DISK='{1}'  
WITH  REPLACE
ALTER DATABASE {0}
SET MULTI_USER;", dataBaseName, dataBaseBackupFile);DataRepository.ExecuteCommand(CommandText);}
View Code

3、帮助类

using ICSharpCode.SharpZipLib.Checksum;
using ICSharpCode.SharpZipLib.Zip;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;namespace swapCommon
{public class ZipUtility{/// <summary>  /// 所有文件缓存  /// </summary>  List<string> files = new List<string>();/// <summary>  /// 所有空目录缓存  /// </summary>  List<string> paths = new List<string>();/// <summary>  /// 压缩单个文件  /// </summary>  /// <param name="fileToZip">要压缩的文件</param>  /// <param name="zipedFile">压缩后的文件全名</param>  /// <param name="compressionLevel">压缩程度,范围0-9,数值越大,压缩程序越高</param>  /// <param name="blockSize">分块大小</param>  public void ZipFile(string fileToZip, string zipedFile, int compressionLevel, int blockSize){if (!System.IO.File.Exists(fileToZip))//如果文件没有找到,则报错  
            {throw new FileNotFoundException("The specified file " + fileToZip + " could not be found. Zipping aborderd");}FileStream streamToZip = new FileStream(fileToZip, FileMode.Open, FileAccess.Read);FileStream zipFile = File.Create(zipedFile);ZipOutputStream zipStream = new ZipOutputStream(zipFile);ZipEntry zipEntry = new ZipEntry(fileToZip);zipStream.PutNextEntry(zipEntry);zipStream.SetLevel(compressionLevel);byte[] buffer = new byte[blockSize];int size = streamToZip.Read(buffer, 0, buffer.Length);zipStream.Write(buffer, 0, size);try{while (size < streamToZip.Length){int sizeRead = streamToZip.Read(buffer, 0, buffer.Length);zipStream.Write(buffer, 0, sizeRead);size += sizeRead;}}catch (Exception ex){GC.Collect();throw ex;}zipStream.Finish();zipStream.Close();streamToZip.Close();GC.Collect();}/// <summary>  /// 压缩目录(包括子目录及所有文件)  /// </summary>  /// <param name="rootPath">要压缩的根目录</param>  /// <param name="destinationPath">保存路径</param>  /// <param name="compressLevel">压缩程度,范围0-9,数值越大,压缩程序越高</param>  public void ZipFileFromDirectory(string rootPath, string destinationPath, int compressLevel){GetAllDirectories(rootPath);/* while (rootPath.LastIndexOf("\\") + 1 == rootPath.Length)//检查路径是否以"\"结尾 { rootPath = rootPath.Substring(0, rootPath.Length - 1);//如果是则去掉末尾的"\" } *///string rootMark = rootPath.Substring(0, rootPath.LastIndexOf("\\") + 1);//得到当前路径的位置,以备压缩时将所压缩内容转变成相对路径。  string rootMark = rootPath + "\\";//得到当前路径的位置,以备压缩时将所压缩内容转变成相对路径。  Crc32 crc = new Crc32();ZipOutputStream outPutStream = new ZipOutputStream(File.Create(destinationPath));outPutStream.SetLevel(compressLevel); // 0 - store only to 9 - means best compression  foreach (string file in files){FileStream fileStream = File.OpenRead(file);//打开压缩文件  byte[] buffer = new byte[fileStream.Length];fileStream.Read(buffer, 0, buffer.Length);ZipEntry entry = new ZipEntry(file.Replace(rootMark, string.Empty));entry.DateTime = DateTime.Now;entry.Size = fileStream.Length;fileStream.Close();crc.Reset();crc.Update(buffer);entry.Crc = crc.Value;outPutStream.PutNextEntry(entry);outPutStream.Write(buffer, 0, buffer.Length);}this.files.Clear();foreach (string emptyPath in paths){ZipEntry entry = new ZipEntry(emptyPath.Replace(rootMark, string.Empty) + "/");outPutStream.PutNextEntry(entry);}this.paths.Clear();outPutStream.Finish();outPutStream.Close();GC.Collect();}/// <summary>  /// 取得目录下所有文件及文件夹,分别存入files及paths  /// </summary>  /// <param name="rootPath">根目录</param>  private void GetAllDirectories(string rootPath){string[] subPaths = Directory.GetDirectories(rootPath);//得到所有子目录  foreach (string path in subPaths){GetAllDirectories(path);//对每一个字目录做与根目录相同的操作:即找到子目录并将当前目录的文件名存入List  
            }string[] files = Directory.GetFiles(rootPath);foreach (string file in files){this.files.Add(file);//将当前目录中的所有文件全名存入文件List  
            }if (subPaths.Length == files.Length && files.Length == 0)//如果是空目录  
            {this.paths.Add(rootPath);//记录空目录  
            }}/// <summary>  /// 解压缩文件(压缩文件中含有子目录)  /// </summary>  /// <param name="zipfilepath">待解压缩的文件路径</param>  /// <param name="unzippath">解压缩到指定目录</param>  /// <returns>解压后的文件列表</returns>  public List<string> UnZip(string zipfilepath, string unzippath){//解压出来的文件列表  List<string> unzipFiles = new List<string>();//检查输出目录是否以“\\”结尾  if (unzippath.EndsWith("\\") == false || unzippath.EndsWith(":\\") == false){unzippath += "\\";}ZipInputStream s = new ZipInputStream(File.OpenRead(zipfilepath));ZipEntry theEntry;while ((theEntry = s.GetNextEntry()) != null){string directoryName = Path.GetDirectoryName(unzippath);string fileName = Path.GetFileName(theEntry.Name);//生成解压目录【用户解压到硬盘根目录时,不需要创建】  if (!string.IsNullOrEmpty(directoryName)){Directory.CreateDirectory(directoryName);}if (fileName != String.Empty){//如果文件的压缩后大小为0那么说明这个文件是空的,因此不需要进行读出写入  if (theEntry.CompressedSize == 0)continue;//解压文件到指定的目录  directoryName = Path.GetDirectoryName(unzippath + fileName);//建立下面的目录和子目录  
                    Directory.CreateDirectory(directoryName);//记录导出的文件  unzipFiles.Add(unzippath + fileName);FileStream streamWriter = File.Create(unzippath + fileName);int size = 2048;byte[] data = new byte[2048];while (true){size = s.Read(data, 0, data.Length);if (size > 0){streamWriter.Write(data, 0, size);}else{break;}}streamWriter.Close();}}s.Close();GC.Collect();return unzipFiles;}public string GetZipFileExtention(string fileFullName){int index = fileFullName.LastIndexOf(".");if (index <= 0){throw new Exception("The source package file is not a compress file");}//extension stringstring ext = fileFullName.Substring(index);if (ext == ".rar" || ext == ".zip"){return ext;}else{throw new Exception("The source package file is not a compress file");}}}
}
View Code

over

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/720353.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

nuxt简单入门安装

参考:https://www.jianshu.com/p/fd99718a63e9 @目录概要具体流程小结 概要 听说直接使用vue写前端对百度的seo不够友好,于是便考虑使用nuxt生成静态化来处理 具体流程 首先你的本机环境要有npm,如下图然后可以使用npx安装nuxt,npx是npm5点几就支持的了,但是我这一开始还不…

工作记录02

1.升降摄像头项目踩坑,红外串口接收时,linux系统下使用read函数是非阻塞接收,当需要接收多字节数据时,会出现只接收到第一个字节的情况 解决办法:改为一次接收一个字节并且加入判断,当需要的数据都接收完全再进行处理或返回

IIS 安装和部署

1. 第一步 2. 第二步: 第三步,把下面这些全安装上 4, 第四步: 在控制面板,将查看方式修改为小图标 5. 找到 "管理工具" 有的电脑叫 "windos工具" 点击进入 6. 找到刚刚安装的IIS 7. 添加网站 8, 根据自己情况配置即可

pdf文件可以转成html网页吗?

目前我们工作或学习中使用最多的可能就是PDF格式的文档了,它虽然有很多好处,但是有时如果文档比较大,传送就比较麻烦,这时我们将其转换成HTML再发送就很方便了。那么pdf格式怎么转html格式呢? 方法一、使用在线pdf转html 如果不想下载软件的话,一些在线工具例如smallpdf中…

鸿蒙HarmonyOS实战-ArkTS语言基础类库(容器类库)

🚀前言 容器类库是指一组用于存储和管理数据的数据结构和算法。它们提供了各种不同类型的容器,如数组、链表、树、图等,以及相关的操作和功能,如查找、插入、删除、排序等。 容器类库还可以包含其他数据结构和算法,如堆、树、图等,以及相关的操作和功能,如排序、查找、…

服务器数据恢复概述

服务器数据恢复概述服务器数据恢复是一个复杂的过程,涉及到多种技术和方法。以下是一些关键步骤和考虑因素:确定数据丢失的原因 在进行数据恢复之前,首先需要确定数据丢失的原因。这可能包括硬件故障、软件错误、病毒攻击、人为操作失误等。了解数据丢失的原因有助于选择合适…

企业文件加密:数据保护的实战策略

数据是企业的生命线,保护数据安全就是保护企业的竞争力。在众多数据保护措施中,文件加密因其直接有效而备受青睐。一、为何文件加密至关重要 在数字化办公时代,企业机密和敏感数据的泄露可能带来毁灭性的后果。文件加密能够确保即使数据被盗,也无法被未授权者访问或解读。 …

【AI应用开发全流程】使用AscendCL开发板完成模型推理

从模型推理需要的开发板环境搭建到执行推理,本文主要是为大家介绍从Ascend910训练到Ascend310推理的昇腾开发全流程。本文分享自华为云社区《【昇腾开发全流程】AscendCL开发板模型推理》,作者:沉迷sk。 前言 学会如何安装配置华为云ModelArts、开发板Atlas 200I DK A2。并打…

springMvc 配置 UReport2

参考:https://blog.csdn.net/qq_42207808/article/details/1122588351.配置pom.xml 引入目前最新得2.2.9版本<dependency><groupId>com.bstek.ureport</groupId><artifactId>ureport2-console</artifactId><version>2.2.9</version>…

S2P医药营销智能管理平台特点和优势

S2P医药营销智能管理平台是正也科技打造的一个专为医药行业设计的综合性营销解决方案,旨在通过智能化、数据驱动的方式提升医药企业的营销效率和效果。以下是关于S2P医药营销智能管理平台的一些主要特点和优势的分析:一、平台特点 数据整合与分析:S2P平台能够整合来自多个渠…

返回顶部按钮的组件

目录1.封装2.调用3.效果 1.封装 <template><transition :name="transitionName"><div v-show="visible" class="back-to-ceiling" @click="backToTop"><svg width="16" height="16" viewBox…