天天看點

備份恢複資料庫

using System;

using System.Data;

using System.Data.SqlClient;

namespace Util

{

    class DbHelper

    {

        public static string DbName { get; set; }

        private static SqlConnection SqlConnection = new SqlConnection("data source=.;Initial Catalog=master;integrated security=SSPI;");

        private static string SqlBackup = "BACKUP DATABASE BookShop TO DISK = 'F:\\ms\\src\\InternetBookstore\\DB\\" + DbName + ".bak'";

        private static string SqlRestore = "Alter database BookShop Set Offline With rollback immediate RESTORE DATABASE BookShop FROM DISK = 'F:\\ms\\src\\InternetBookstore\\DB\\" + DbName + ".bak' Alter database BookShop Set Online With Rollback immediate";

        private SqlCommand SqlCommandBackup     = new SqlCommand() { Connection = SqlConnection, CommandType = CommandType.Text, CommandText = SqlBackup };

        private SqlCommand SqlCommandRestore    = new SqlCommand() { Connection = SqlConnection, CommandType = CommandType.Text, CommandText = SqlRestore };

        public void DbBackup()

        {

            SqlConnection.Open();

            try

            {

                SqlCommandBackup.ExecuteNonQuery();

            }

            catch (Exception e)

            {

                string str = e.Message;

                SqlConnection.Close();

            }

            SqlConnection.Close();

        }

        public void DbRestore()

        {

            SqlConnection.Open();

            try

            {

                SqlCommandRestore.ExecuteNonQuery();

            }

            catch (Exception e)

            {

                string str = e.Message;

                SqlConnection.Close();

            }

            SqlConnection.Close();

        }

    }

}