zoukankan      html  css  js  c++  java
  • C#实现对数据库的备份还原(完全)

    C#实现对数据库的备份还原

           ( 用SQL语句实现对数据库备份还原操作

           备份SqlServer数据库:
      backup database 数据库名 to disk (备份文件存放路径+文件名).bak

      还原SqlServer数据库:
      string path = this.FileUpload1.PostedFile.FileName; //获得备份路径及数据库名称 
      use master restore database 数据库名 from disk='" + path + "'"; )

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Text;
    using System.Windows.Forms;
    using System.Collections;
    using System.Data.Sql;
    using System.IO;


    namespace 数据库备份
    {
        public partial class Form1 : Form
        {
            //需要添加一个引用C:Program FilesMicrosoft SQL Server80ToolsBinn下的SQLDMO.DLL;
            //SQL默认安装下是在以上路径
            //备份的文件放在C:Program FilesMicrosoft SQL ServerMSSQLBACKUP下
            string ServerName = "";
            string UserName = "sa";//暂时锁定,可以根据需要自己设置
            string Password = "sa";
           
            public Form1()
            {
                InitializeComponent();
                
            }
            //获取服务器列表
            public ArrayList GetServerList()
            {
                ArrayList alServers = new ArrayList();
               
                SQLDMO.Application sqlApp = new SQLDMO.ApplicationClass();
                try
                {
                    SQLDMO.NameList serverList = sqlApp.ListAvailableSQLServers();
                    for (int i = 1; i <= serverList.Count; i++)
                    {
                        alServers.Add(serverList.Item(i));
                        //comboBox1.Items.Add(serverList.Item(i));
                        listBox1.Items.Add(serverList.Item(i));
                        
                    }
                }
                catch (Exception e)
                {
                    throw (new Exception("取数据库服务器列表出错:" + e.Message));
                }
                finally
                {
                    sqlApp.Quit();
                }
                return alServers;
            }
            //获取数据库列表
            public ArrayList GetDbList(string strServerName, string strUserName, string strPwd)
            {
                string ServerName = strServerName;
                string UserName = strUserName;
                string Password = strPwd;

                ArrayList alDbs = new ArrayList();
                SQLDMO.Application sqlApp = new SQLDMO.ApplicationClass();
                SQLDMO.SQLServer svr = new SQLDMO.SQLServerClass();
                try
                {
                    svr.Connect(ServerName, UserName, Password);
                    foreach (SQLDMO.Database db in svr.Databases)
                    {
                        if (db.Name != null)
                            alDbs.Add(db.Name);
                        listBox2.Items.Add(db.Name);
                    }
                }
                catch (Exception e)
                {
                    MessageBox.Show("连接数据库出错:" + e.Message);
                }
                finally
                {
                    svr.DisConnect();
                    sqlApp.Quit();
                }
                return alDbs;
            }
            //备份数据
            public bool BackUPDB(string strDbName, string strFileName, ProgressBar pgbMain)
            {
                ProgressBar PBar = pgbMain;
                SQLDMO.SQLServer svr = new SQLDMO.SQLServerClass();
                try
                {
                    svr.Connect(ServerName, UserName, Password);
                    SQLDMO.Backup bak = new SQLDMO.BackupClass();
                    bak.Action = 0;
                    bak.Initialize = true;
                    SQLDMO.BackupSink_PercentCompleteEventHandler pceh = new SQLDMO.BackupSink_PercentCompleteEventHandler(Step);
                    bak.PercentComplete += pceh;
                    bak.Files = strFileName;//这里可以写成路径+文件名形式,自己写!
                    bak.Database = strDbName;
                    bak.SQLBackup(svr);
                    return true;
                }
                catch (Exception err)
                {
                    throw (new Exception("备份数据库失败" + err.Message));
                }
                finally
                {
                    svr.DisConnect();
                }
            }
            //进度条
            private void Step(string message, int percent)
            {
                PBar.Visible = true;
                 PBar.Value = percent;
            }
            //还原数据
            public bool RestoreDB(string strDbName, string strFileName, ProgressBar pgbMain)
            {
                ProgressBar PBar = pgbMain;
                SQLDMO.SQLServer svr = new SQLDMO.SQLServerClass();
                try
                {
                    svr.Connect(ServerName, UserName, Password);
                    SQLDMO.QueryResults qr = svr.EnumProcesses(-1);
                    int iColPIDNum = -1;
                    int iColDbName = -1;
                    for (int i = 1; i <= qr.Columns; i++)
                    {
                        string strName = qr.get_ColumnName(i);
                        if (strName.ToUpper().Trim() == "SPID")
                        {
                            iColPIDNum = i;
                        }
                        else if (strName.ToUpper().Trim() == "DBNAME")
                        {
                            iColDbName = i;
                        }
                        if (iColPIDNum != -1 && iColDbName != -1)
                            break;
                    }

                    for (int i = 1; i <= qr.Rows; i++)
                    {
                        int lPID = qr.GetColumnLong(i, iColPIDNum);
                        string strDBName = qr.GetColumnString(i, iColDbName);
                        if (strDBName.ToUpper() == strDbName.ToUpper())
                            svr.KillProcess(lPID);
                    }

                    SQLDMO.Restore res = new SQLDMO.RestoreClass();
                    res.Action = 0;
                    SQLDMO.RestoreSink_PercentCompleteEventHandler pceh = new SQLDMO.RestoreSink_PercentCompleteEventHandler(Step);
                    res.PercentComplete += pceh;
                    res.Files = strFileName;//可以写成路径+文件名

                    res.Database = strDbName;
                    res.ReplaceDatabase = true;
                    res.SQLRestore(svr);
                    return true;
                }
                catch (Exception err)
                {
                    throw (new Exception("恢复数据库失败,请关闭所有和该数据库连接的程序!" + err.Message));
                }
                finally
                {
                    svr.DisConnect();
                }
            }

            private void Form1_Load(object sender, EventArgs e)
            {
                GetServerList();
                string ServerName = "(local)";//这里根据需要自己可以设置成动态的
                GetDbList(ServerName, UserName, Password);
            }
            //根据选择的服务器,列出数据库
            private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
            {    //这里可以动态设置服务器名,角色名,密码
                //string ServerName = listBox1.SelectedItem.ToString();
                //GetDbList(ServerName, UserName, Password);
               
            }

            private void SelectPath_Click(object sender, EventArgs e)
            { 
                //选择保存路径
                //if (folderBrowserDialog1.ShowDialog(this) == DialogResult.OK)
                //{
                //    string path = folderBrowserDialog1.SelectedPath + "\";
                //    txtPath.Text = path;
                   
                //}
                //else
                //{
                //   folderBrowserDialog1.Dispose();
                //}
            }
            //备份按钮
            private void btnSave_Click(object sender, EventArgs e)
            {
                string strDbName = "db_bookmanage";
                txtSaveName.Text = DateTime.Now.ToString("yyyyMMddhhmmss");
                string strFileName = txtSaveName.Text.ToString().Trim();
                if (BackUPDB(strDbName, strFileName, PBar))
                {
                    PBar.Visible = false;
                    MessageBox.Show("备份完成!");
                }
               
            }
            //查看历史备份按钮
            private void button2_Click(object sender, EventArgs e)
            {
                listBox3.Items.Clear();
                string[] files = Directory.GetFiles(@"C:Program FilesMicrosoft SQL ServerMSSQLBACKUP");
                foreach (string file in files)
                    listBox3.Items.Add(file.Substring(file.LastIndexOf("\") + 1, file.Length - file.LastIndexOf("\") - 1));
            }
            //还原数据按钮
            private void button1_Click(object sender, EventArgs e)
            {
                PBar.Visible = true;
                string strDbName = "db_bookmanage";
                //txtSaveName.Text = DateTime.Now.ToString("yyyyMMddhhmmss");
                if (txtReName.Text == "")
                {
                    MessageBox.Show("请选择一个要还原的文件!");
                    return;
                }
                string strFileName = txtReName.Text.ToString().Trim();
                if (RestoreDB(strDbName, strFileName, PBar))
                {
                    PBar.Visible = false;
                    MessageBox.Show("还原完成!");
                }
            }
            //历史备份文件名
            private void listBox3_SelectedIndexChanged(object sender, EventArgs e)
            {
                txtReName.Text = listBox3.SelectedItem.ToString();
            }   

            
        }
    }

  • 相关阅读:
    linux系统常用命令
    python文件处理
    Python按行读文件
    向脚本传递参数-shift命令
    shell脚本中一些特殊符号
    标准make变量 MAKE_VERSION, CURDIR
    makefile "=" ":=" "?=" "+="
    静态资源映射
    Spring MVC的常用注解
    SpringMVC项目的快速搭建
  • 原文地址:https://www.cnblogs.com/meimao5211/p/3339881.html
Copyright © 2011-2022 走看看