zoukankan      html  css  js  c++  java
  • 关于 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("无法连接服务器!
    " + 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:报错原因也有可能是当前用户缺少了对应文件夹的写入权限,可以按照参考博客里写的一步步排查。

  • 相关阅读:
    背水一战 Windows 10 (26)
    背水一战 Windows 10 (25)
    背水一战 Windows 10 (24)
    背水一战 Windows 10 (23)
    背水一战 Windows 10 (22)
    背水一战 Windows 10 (21)
    背水一战 Windows 10 (20)
    背水一战 Windows 10 (19)
    背水一战 Windows 10 (18)
    背水一战 Windows 10 (17)
  • 原文地址:https://www.cnblogs.com/Sunny20181123/p/10999138.html
Copyright © 2011-2022 走看看