C# sqlserver 數據庫備份與還原(winform版)

數據庫備份與還原的sql語句

//數據庫備份
backup database northwind to disk='c:\dbbackup\northwind.bak';
//數據庫還原
//數據庫還原
use master;
alter database northwind set offline with rollback immediate 
restore database northwind from disk='c:\dbbackup\northwind.bak' 
alter database northwind set online with rollback immediate;

winform界面設計

在這裏插入圖片描述

代碼

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SqlBackupAndRestore
{
    public partial class FrmBackup : Form
    {
        public string strConnection { get; set; }
        public FrmBackup()
        {
            InitializeComponent();
            //默認數據庫名稱和備份路徑
            txtDBName.Text = "northwind";
            txtBackupPath.Text = @"c:\dbbackup";
            strConnection = ConfigurationManager.ConnectionStrings["sqlserver"].ConnectionString;
            GetBackupFiles(txtBackupPath.Text);
        }

        /// <summary>
        /// 選擇數據庫備份路徑
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSelect_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dialog = new FolderBrowserDialog();
            dialog.Description = "請選擇數據庫備份所在文件夾";
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                if (string.IsNullOrEmpty(dialog.SelectedPath))
                {
                    MessageBox.Show(this, "文件夾路徑不能爲空", "提示");
                    return;
                }
                txtBackupPath.Text = dialog.SelectedPath;
                GetBackupFiles(txtBackupPath.Text);
            }
        }

        /// <summary>
        /// 獲取所有數據庫備份
        /// </summary>
        /// <param name="path"></param>
        private void GetBackupFiles(string path)
        {
            string[] files = Directory.GetFiles(path, "*.bak");
            lbBackups.Items.Clear();
            lbBackups.Items.AddRange(files);
        }

        /// <summary>
        /// 數據庫備份
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnBackup_Click(object sender, EventArgs e)
        {
            //數據庫名稱
            if (string.IsNullOrEmpty(txtDBName.Text))
            {
                MessageBox.Show("請輸入需要備份的數據庫名稱!","提示",MessageBoxButtons.OK,MessageBoxIcon.Warning);
                return;
            }
            if (string.IsNullOrEmpty(txtBackupPath.Text))
            {
                MessageBox.Show("請輸入存放備份的目錄!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            else if (!Directory.Exists(txtBackupPath.Text))
            {
                MessageBox.Show("路徑不存在");
                return;
            }
            else
            {
                //yyyyMMddHHmmss爲24小時制,yyyyMMddhhmmss爲12小時制
                string backFile = txtDBName.Text + DateTime.Now.ToString("yyyyMMddHHmmss") + ".bak";
                DbBackupHelper.BackupDataBase(strConnection, txtDBName.Text, txtBackupPath.Text, backFile);
                GetBackupFiles(txtBackupPath.Text);
                MessageBox.Show("備份成功", "結果", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

        }

        /// <summary>
        /// 數據庫還原
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRestore_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtDBName.Text))
            {
                MessageBox.Show("請先輸入數據庫名稱", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else if (lbBackups.SelectedItem == null)
            {
                MessageBox.Show("請先選擇需要還原的備份文件!");
            }
            else if (!File.Exists(lbBackups.SelectedItem.ToString()))
            {
                MessageBox.Show("備份文件不存在!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else
            {
                DbBackupHelper.RestoreDataBase(strConnection,txtDBName.Text, lbBackups.SelectedItem.ToString());
                MessageBox.Show("數據庫還原成功!", "結果", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
        }
    }
}

DBBackupHelper代碼:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SqlBackupAndRestore
{
    public class DbBackupHelper
    {
        /// <summary>
        /// 還原數據庫
        /// </summary>
        public static bool RestoreDataBase(string connectionString, string dataBaseName, string dataBaseBackupFile)
        {
            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                conn.Open();
                SqlCommand comm = new SqlCommand();
                comm.Connection = conn;

                //comm.CommandText = "use master;restore database @DataBaseName From disk = @BackupFile with replace;";
                // alter database不支持參數化語法
                comm.CommandText = "use master;alter database " + dataBaseName + " set offline with rollback immediate; restore database " + dataBaseName + " from disk='" + dataBaseBackupFile + "' with replace;alter database  " + dataBaseName + " set online with rollback immediate";
                //comm.CommandText = "use master;alter database @dataBaseName set offline with rollback immediate; restore database @dataBaseName from disk='@backupFile' with replace;alter database  @dataBaseName set online with rollback immediate";
                //comm.Parameters.Add(new SqlParameter("dataBaseName", SqlDbType.NVarChar));
                //comm.Parameters["dataBaseName"].Value = dataBaseName;
                //comm.Parameters.Add(new SqlParameter("backupFile", SqlDbType.NVarChar));
                //comm.Parameters["backupFile"].Value = dataBaseBackupFile;
                comm.CommandType = CommandType.Text;
                comm.ExecuteNonQuery();
            }
            return true;
        }

        /// <summary>
        /// 備份SqlServer數據庫
        /// </summary>
        public static bool BackupDataBase(string connectionString, string dataBaseName, string backupPath, string backupName)
        {
            string filePath = Path.Combine(backupPath, backupName);
            if (File.Exists(filePath))
            {
                File.Delete(filePath);
            }

            using (SqlConnection conn = new SqlConnection(connectionString))
            {
                conn.Open();
                SqlCommand comm = new SqlCommand();
                comm.Connection = conn;
                comm.CommandText = "use master;backup database @dbname to disk = @backupname;";
                comm.Parameters.Add(new SqlParameter("dbname", SqlDbType.NVarChar));
                comm.Parameters["dbname"].Value = dataBaseName;
                comm.Parameters.Add(new SqlParameter("backupname", SqlDbType.NVarChar));
                comm.Parameters["backupname"].Value = filePath;
                comm.CommandType = CommandType.Text;
                comm.ExecuteNonQuery();
            }
            return true;
        }

    }
}

參考:

  1. 出現“System.Data.SqlClient.SqlError: 尚未備份數據庫的日誌尾部”錯誤的解決方案: https://www.cnblogs.com/feiyuhuo/p/5514344.html
    在這裏插入圖片描述
  2. 數據庫備份錯誤
    這個是因爲備份數據庫時,應用程序還在連接數據庫,需要先斷開數據庫在這裏插入圖片描述
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章