c#备份还原MSSQL数据库

Posted nbu_djw

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c#备份还原MSSQL数据库相关的知识,希望对你有一定的参考价值。

public void backup()
        {
            SqlConnection conn = new SqlConnection("Server=.;Database=master;User ID=sa;Password=1q2w3e4r");
            SqlCommand cmd = new SqlCommand();
            cmd.CommandType = CommandType.Text;
            cmd.Connection = conn;
            cmd.CommandText = @"backup database testBackUp to disk=‘D:backupdb‘ with init ";

            try
            {
                conn.Open();
                cmd.ExecuteNonQuery();
            }
            catch (Exception e)
            {

                //throw;
            }
            finally
            {
                conn.Close();
                conn.Dispose();
            }
        }

        public void restore()
        {
            SqlConnection conn = new SqlConnection("Server=.;Database=master;User ID=sa;Password=1q2w3e4r;Trusted_Connection=False");
            conn.Open();
            SqlCommand cmd = new SqlCommand("SELECT spid FROM sysprocesses ,sysdatabases WHERE sysprocesses.dbid=sysdatabases.dbid AND sysdatabases.Name=‘testBackUp‘", conn);

            SqlDataReader dr = cmd.ExecuteReader();
            ArrayList list = new ArrayList();
            while (dr.Read())
            {
                list.Add(dr.GetInt16(0));
            }
            dr.Close();
            for (int i = 0; i < list.Count; i++)
            {
                cmd = new SqlCommand(string.Format("KILL {0}", list[i]), conn);
                cmd.ExecuteNonQuery();
            }

            SqlCommand c = new SqlCommand();
            c.CommandType = CommandType.Text;
            c.Connection = conn;
            //with REPLACE very important
            c.CommandText = @"restore database testBackUp  from disk=‘D:backupdb‘ with REPLACE";

            try
            {
                c.ExecuteNonQuery();
            }
            catch (Exception e)
            {

                //throw;
            }
            finally
            {
                conn.Close();
            }
        }

 

以上是关于c#备份还原MSSQL数据库的主要内容,如果未能解决你的问题,请参考以下文章

MSSQL备份文件怎么还原到新数据库

mssql sqlserver 快速表备份和表还原的方法

MSSQL2000的BAT备份文件怎么恢复

MSSQL Server 数据库备份还原常用SQL语句及注意

MSSQL Server 数据库备份还原常用SQL语句及注意

sql sever 2008数据库的还原备份问题