时间:2021-07-01 10:21:17 帮助过:5人阅读
其中,<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:报错原因也有可能是当前用户缺少了对应文件夹的写入权限,可以按照参考博客里写的一步步排查。
关于 SQL Server 数据库批量备份与还原的一些 Tips
标签:set 点击 enc 选项 string bak 自己 serve 报错