关于 SQL Server 数据库批量备份与还原的一些 Tips

一、前提

      最近需要将服务器 A 上的数据库全部备份,并在服务器 B 上进行还原,30多个数据库一个一个地用鼠标点,先是 backup,之后时 restore……整个过程实在是太浪费时间了!于是直接写一个小工具来批量备份还原数据库,也可以结合 Windows 的任务计划来做一个自动备份,这里记录一下一些 Tips,方便自己以后查看。

 

二、写配置文件

      首先,我将数据库连接字符串和自动备份的目录路径写在了配置文件里,方便在以后数据库连接或者存储目录变动时,直接修改配置文件里的对应值就可以了。 App.config 具体结构如下:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
    </startup>
  <connectionStrings>
    <add name="DBConnection" connectionString="Data Source=localhost;Initial Catalog=master;User ID=sa;PassWord=123456"/>
  </connectionStrings>
  <appSettings>
    <add key ="BackupPath" value="C:\dbbackup"/>
  </appSettings>
</configuration>

      其中,<connectionStrings>里配置了数据库连接,使用了 master 数据库来创建连接;<appSettings>里配置了自动备份路径。

      Note:上面的连接字符串使用的是 SQL Server 身份验证,若想使用 Windows 验证,字符串如下:

<connectionStrings>
    <add name="DBConnection" connectionString="Data Source=localhost;Initial Catalog=master;integrated security=true"/>
</connectionStrings>

 

三、读取配置文件

      在 C# 里读取 App.config 文件,获取对应的 value,具体代码如下:

using System.Configuration;

//读取config文件里的配置字符串
private static string connStr = ConfigurationManager.ConnectionStrings["DBConnection"].ConnectionString; //自动备份的目录 private string autoPath = ConfigurationManager.AppSettings["BackupPath"];

 

四、获取当前服务器中的所有数据库名称

List<string> list_dataBases = new List<string>();
list_dataBases.Clear();
using (SqlConnection conn = new SqlConnection(connStr))
{
    try
    {
        conn.Open();
        SqlCommand cmd = new SqlCommand();
        cmd.Connection = conn;
        cmd.CommandText = "select name from sysdatabases";  //查询所有的数据库名称
        SqlDataReader dataReader = cmd.ExecuteReader();
        while (dataReader.Read())
        {
            list_dataBases.Add(dataReader.GetString(0));
        }
    }
    catch (Exception ex)
    {
        Console.WriteLine("无法连接服务器!\n" + ex.Message);
    }
}

 

五、备份数据库

DirectoryInfo autoDirectoryInfo = new DirectoryInfo(autoPath);
if (!autoDirectoryInfo.Exists)
{
    autoDirectoryInfo.Create();
}
foreach(string dbName in list_dataBases) { bool bSuccess = false;
try { //备份数据库 using (SqlConnection conn = new SqlConnection(connStr)) { conn.Open(); SqlCommand cmd = new SqlCommand(); cmd.Connection = conn; cmd.CommandText = @"backup database " + dbName + " to disk='" + autoPath + @"\" + dbName + ".bak'"; cmd.ExecuteNonQuery(); bSuccess = true; conn.Dispose(); } } catch (Exception ex) { Console.WriteLine("数据库:" + dbName + "备份失败!"); Console.WriteLine("Error Message: " + ex.Message); } finally { if (bSuccess) { Console.WriteLine("数据库:" + dbName + "备份成功!"); bSuccess = false; } } }

 

六、还原数据库

      代码跟备份功能基本一致,只需修改下 SQL 语句,将 backup 改成 restore:

cmd.CommandText = @"restore database " + dbName + " from disk='" + savePath + @"\" + dbName + ".bak'"; //savePath 是存放 bak 文件的文件夹路径

 

七、可能出现的问题

备份数据库时可能会报以下错误:Cannot open backup device ‘<PathFilename>’. Operating system error 3 (The system cannot find the path specified).

解决方案:

参考博客:https://sqlbackupandftp.com/blog/how-to-solve-operating-system-error-3

① win + R -> 输入:services.msc

 

② 找到 SQL Server 服务,双击:

 

③ 点击 Log On 选项卡,将 Log on as 改为:Local System account

 

④ 右键重启服务,再重新运行备份程序,这个时候就不会再报错了,备份完成。

 

Note:报错原因也有可能是当前用户缺少了对应文件夹的写入权限,可以按照参考博客里写的一步步排查。

转载于:https://www.cnblogs.com/Sunny20181123/p/10999138.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值