天天看點

c#實作資料庫的備份

在.NET開發後天管理系統的時候,資料庫的備份功能是必須實作的一塊,而在資料庫備份方面一句sql語句就可以搞定了,那就是<Backup Database 資料庫名To disk='路徑資料庫備份名.bak' >。基于此語句開始實作備份功能。

首先需要封裝一個連接配接資料庫的help類

   public SqlEmploy()
    { }
    public string MyConnStr
    {
        get
        {
                 return System.Configuration.ConfigurationManager.ConnectionStrings["SHDSConnectionString"].ToString();
        }
    }

    public int Back_up(string sql, SqlParameter[] para, CommandType type)
    {
        SqlConnection conn = new SqlConnection(MyConnStr);
        try
        {
            SqlCommand cmd = new SqlCommand(sql, conn);
            if (conn.State == ConnectionState.Closed || conn.State == ConnectionState.Broken)
            {
                conn.Open();
            }

            if (para != null && para.Length > 0)
            {
                foreach (SqlParameter p in para)
                {
                    cmd.Parameters.Add(p);
                }
            }

            cmd.CommandType = type;
            int count = cmd.ExecuteNonQuery();
            return count;
        }
        finally
        {
            conn.Close();
        }
    }
      

  然後我們選擇一個Button控件,寫一個Click方法

protected void Button1_Click(object sender, EventArgs e)
    {
        string newname = "SHDH" + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + ".bak";       
        string nepath = Server.MapPath("~/DataBack/") + newname;
        string sql = "BACKUP DATABASE SHDS to DISK ='" + nepath + "'";
        int i = help.Back_up(sql,null,System.Data.CommandType.Text);
        if (i==-1)
        {
            Label1.Text = "已成功備份到伺服器路徑:" + nepath;

        }
        else
        {
            Label1.Text = "備份資料庫出錯,該檔案可能不存在!";
            Label1.Visible = true;
        }

    }
      

  為什麼上面的i是-1,這個我想大家一定有疑問,我在檢視ExecuteNonQuery()方法的時候,有這樣一句話“ExecuteNonQuery()方法對資料庫結構的操作,如果操作成功時傳回的卻是-1”是以,在基本的資料操作ExecuteNonQuery()方法傳回的就是影響的資料行數,而在操作資料庫結構之類的方面,他成功之後傳回的就是-1,是以i==-1。