數據庫讀取和恢復,測試中。。。。

来源:互联网 发布:龙源数据库论文检索 编辑:程序博客网 时间:2024/05/16 08:17

 protected void BackBase()//備份數據庫
    {
        SqlConnection conn = new SqlConnection("Server=.;Database=master;User ID=sa;Password=sa;");

        SqlCommand cmdBK = new SqlCommand();
        cmdBK.CommandType = CommandType.Text;
        cmdBK.Connection = conn;
        cmdBK.CommandText = @"backup database test to disk='C:/ba' with init";

        try
        {
            conn.Open();
            cmdBK.ExecuteNonQuery();
            MessageBox.Show("Backup successed.");
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            conn.Close();
            conn.Dispose();
        }

 

        SqlConnection conn = new SqlConnection("Server=.;Database=master;User ID=sa;Password=sa;Trusted_Connection=False");
        conn.Open();

        //KILL DataBase Process
        SqlCommand cmd = new SqlCommand("SELECT spid FROM sysprocesses ,sysdatabases WHERE sysprocesses.dbid=sysdatabases.dbid AND sysdatabases.Name='test'", conn);
        SqlDataReader dr;
        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), conn);
            cmd.ExecuteNonQuery();
        }
            //恢復數據庫 
        SqlCommand cmdRT = new SqlCommand();
        cmdRT.CommandType = CommandType.Text;
        cmdRT.Connection = conn;
        cmdRT.CommandText = @"restore database test from disk='C:/ba'";

        try
        {
            cmdRT.ExecuteNonQuery();
            MessageBox.Show("Restore successed.");
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        finally
        {
            conn.Close();
        }
    }