C\#SqlServer 데이터베이스 백업 및 복원 실현

23464 단어 C#SqlServer
C\#sqlserver 데이터 베 이 스 를 백업 하고 복원 할 때 master 데이터 베 이 스 를 사용 하여 조작 하 는 것 이 좋 습 니 다.다음은 백업 과 복원 코드 입 니 다.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;

namespace WindowsFormsApplication1
{
    public partial class Form1 : Form
    {
        //      
        private string connectionString = "Data Source=DSF-PC;Initial Catalog=master;User ID=sa;Password=123456";

        //     
        public Form1()
        {
            InitializeComponent();
        }

        //   
        private void btnBackup_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Title = "     ";
            saveFileDialog.Filter = "    (*.bak)|*.bak";
            saveFileDialog.RestoreDirectory = true;
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                bool ok = Backup("Test", saveFileDialog.FileName);
                if (ok)
                {
                    MessageBox.Show("    ");
                }
                else
                {
                    MessageBox.Show("    ");
                }
            }
        }

        //   
        private void btnRestore_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Title = "     ";
            openFileDialog.Filter = "    (*.bak)|*.bak";
            openFileDialog.RestoreDirectory = true;
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                bool ok = Restore("Test", openFileDialog.FileName);
                if (ok)
                {
                    MessageBox.Show("    ");
                }
                else
                {
                    MessageBox.Show("    ");
                }
            }
        }

        //      
        private bool Backup(string dbName, string filePath)
        {
            SqlConnection connection = new SqlConnection();
            connection.ConnectionString = connectionString;
            connection.Open();

            SqlCommand command = new SqlCommand();
            command.Connection = connection;
            command.CommandText = string.Format("backup database {0} to disk = '{1}'", dbName, filePath);

            try
            {
                command.ExecuteNonQuery();
                return true;
            }
            catch
            {
                return false;
            }
            finally
            {
                connection.Close();
            }
        }

        //      
        private bool Restore(string dbName, string filePath)
        {
            SqlConnection connection = new SqlConnection();
            connection.ConnectionString = connectionString;
            connection.Open();

            SqlCommand command = new SqlCommand();
            command.Connection = connection;
            command.CommandText = string.Format("select spid from sysprocesses,sysdatabases where sysprocesses.dbid=sysdatabases.dbid and sysdatabases.Name='{0}'", dbName);

            //           
            List<short> list = new List<short>();
            try
            {
                SqlDataReader reader = command.ExecuteReader();
                while (reader.Read())
                {
                    list.Add(reader.GetInt16(0));
                }
                reader.Close();
            }
            catch
            {
                return false;
            }
            finally
            {
                connection.Close();
            }

            //           
            try
            {
                for (int i = 0; i < list.Count; i++)
                {
                    connection.Open();
                    command = new SqlCommand(string.Format("kill {0}", list[i].ToString()), connection);
                    command.ExecuteNonQuery();
                    connection.Close();
                }
            }
            catch
            {
                return false;
            }
            finally
            {
                connection.Close();
            }

            //      
            connection.Open();
            command.CommandText = string.Format("restore database {0} from disk = '{1}' with replace", dbName, filePath);
            try
            {
                command.ExecuteNonQuery();
            }
            catch
            {
                return false;
            }
            finally
            {
                connection.Close();
            }
            return true;
        }
    }
}

좋은 웹페이지 즐겨찾기