1. 程式人生 > 其它 >sqlserver 備份還原資料庫

sqlserver 備份還原資料庫

using Chloe.SqlServer;
using System;
using System.Collections.Generic;
using System.IO;
namespace bak
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("還原/備份(restore/backup):");
            var rep = Console.ReadLine();
            while (!(rep.ToLower() == "
restore" || rep.ToLower() == "backup")) { Console.WriteLine("還原/備份(restore/backup)輸入restore或backup繼續:"); rep = Console.ReadLine(); } if (rep == "restore") { restore(); } else if (rep == "
backup") { backUp(); } else { Console.WriteLine("結束"); } Console.ReadKey(); } static void backUp() { string connStr = "data source=.;user id=sa;password=ld123456a*;initial catalog=master
"; Console.WriteLine(string.Concat("預設連線字串:", connStr)); Console.Write("請輸入連線字串(按Enter選擇預設連線字串):"); var newconstr = Console.ReadLine(); if (string.IsNullOrEmpty(newconstr)) { Console.WriteLine(string.Concat("當前所選擇的連線字串為:", connStr)); } else { connStr = newconstr; Console.WriteLine("當前所選擇的連線字串為:", connStr); } Console.Write("請輸入備份路徑:"); var dir = Console.ReadLine(); while (string.IsNullOrEmpty(dir) || !Directory.Exists(dir)) { Console.Write("輸入的路徑有錯誤,請輸入備份路徑:"); dir = Console.ReadLine(); } Console.Write("請輸入要備份的資料庫,以【 , 】分割,預設全部庫,按回車確認:"); var databaseStr = Console.ReadLine().Replace("",","); var databases = databaseStr.Split(','); var willbackup = new List<string>(); var uselessdatabase = new List<string>(); if (!string.IsNullOrEmpty(databaseStr)) { //備份全部資料庫 //查詢每個看看資料庫是否都存在 foreach (var item in databases) { if (!string.IsNullOrEmpty(item)) { using (MsSqlContext context = new MsSqlContext(connStr)) { var obj = context.SqlQuery<dynamic>($"select top 1 * from sys.databases where name = '{item.Trim()}'"); if (obj.Count > 0) { willbackup.Add(item.Trim()); } else { uselessdatabase.Add(item.Trim()); } } } } } else { using (MsSqlContext context = new MsSqlContext(connStr)) { willbackup = context.SqlQuery<string>($"select name from sys.databases where database_id > 4"); } } Console.WriteLine(string.Concat("將備份的資料庫為:", string.Join(',', willbackup))); if (uselessdatabase.Count > 0) { Console.WriteLine(string.Concat("以下資料庫不存在將跳過:", string.Join(',', uselessdatabase))); } Console.WriteLine("是否繼續(y/n):"); var contiue = false; var cont = Console.ReadLine(); while (!(cont.ToLower() == "y" || cont.ToLower() == "n")) { Console.WriteLine("是否繼續(y/n):"); cont = Console.ReadLine(); } contiue = cont == "y" ? true : false; if (contiue) { foreach (var item in willbackup) { string fileName = Path.Combine(dir,string.Concat(DateTime.Now.ToString("yyyy-MM-dd-hhmmssss_"), item, ".bak")); try { using (MsSqlContext context = new MsSqlContext(connStr)) { context.Session.CommandTimeout = int.MaxValue; context.SqlQuery<dynamic>(@$" BACKUP DATABASE [{item}] TO DISK = '{fileName}' WITH NOFORMAT, NOINIT, NAME = N'{item}-完整 資料庫 備份', SKIP, NOREWIND, NOUNLOAD"); } Console.WriteLine($"資料庫{item}備份成功"); } catch (Exception ex) { Console.WriteLine($"資料庫{item}備份失敗---{ex.Message}"); } } Console.WriteLine($"備份執行結束"); } else { Console.WriteLine("結束"); } } static void restore() { string connStr = "data source=.;user id=sa;password=ld123456a*;initial catalog=master"; Console.WriteLine(string.Concat("預設連線字串:", connStr)); Console.Write("請輸入連線字串(按Enter選擇預設連線字串):"); var newconstr = Console.ReadLine(); if (string.IsNullOrEmpty(newconstr)) { Console.WriteLine(string.Concat("當前所選擇的連線字串為:", connStr)); } else { connStr = newconstr; Console.WriteLine("當前所選擇的連線字串為:", connStr); } Console.Write("請輸入bak所在路徑:"); var dir = Console.ReadLine(); while (string.IsNullOrEmpty(dir) || !Directory.Exists(dir)) { Console.Write("輸入的路徑有錯誤,請輸入bak所在路徑:"); dir = Console.ReadLine(); } Console.Write("請輸入還原後的路徑:"); var recoverDir = Console.ReadLine(); while (string.IsNullOrEmpty(recoverDir) || !Directory.Exists(recoverDir)) { Console.Write("輸入的路徑有錯誤,請輸入還原後的路徑:"); recoverDir = Console.ReadLine(); } Console.WriteLine("是否覆蓋(y/n):"); var replace = false; var rep = Console.ReadLine(); while (!(rep.ToLower() == "y" || rep.ToLower() == "n")) { Console.WriteLine("是否覆蓋(y/n):"); rep = Console.ReadLine(); } replace = rep == "y" ? true : false; string[] files = Directory.GetFiles(dir); foreach (var item in files) { try { using (MsSqlContext context = new MsSqlContext(connStr)) { context.Session.CommandTimeout = int.MaxValue; var headInfo = context.SqlQuery<dynamic>($"RESTORE HEADERONLY FROM DISK = '{item}'"); var fileInfo = context.SqlQuery<dynamic>($"RESTORE FILELISTONLY from disk= N'{item}'"); if (headInfo.Count < 1) { Console.WriteLine($"檔案,{item},還原失敗"); continue; } else { var databaseName = headInfo[0].DatabaseName; var dataName = fileInfo[0].LogicalName; var logName = fileInfo[1].LogicalName; string restorSql = $@"RESTORE DATABASE {databaseName} from disk= N'{item}' WITH NOUNLOAD, {(replace ? "REPLACE," : "")} MOVE '{dataName}' TO '{Path.Combine(recoverDir, string.Concat(databaseName, ".mdf"))}', MOVE '{logName}' TO '{Path.Combine(recoverDir, string.Concat(databaseName, ".ldf"))}';"; Console.WriteLine($"正在還原{databaseName}"); context.SqlQuery<dynamic>(restorSql); Console.WriteLine($"還原{databaseName}成功"); } } } catch (Exception ex) { Console.WriteLine(ex); } } Console.WriteLine($"還原執行結束"); } } }
View Code