Asp.net線上備份、壓縮和修複Access資料庫

來源:互聯網
上載者:User

1.問題的提出

在設計中小型Web應用程式時,可以選擇Microsoft Accesss為資料庫。在資料庫的使用過程中經常性進行增加和刪除操作。事實上,Microsoft Access並不能有效地釋放已指派的但被刪除的對象空間,這將意味著即使你刪除了一個對象,而這個對象仍然佔據著資料庫的空間,使得資料庫越來越大。不但佔用不必要的空間,而且降低了資料庫的效率。特別在虛擬網站上的問題尤為突出。因此對Access資料庫進行壓縮瘦身很有實際意義。
雖然Access資料庫自身具有“壓縮和修複資料庫”功能(工具è資料庫工具 + 生產力è壓縮和修複資料庫)。但對一般使用者來說操作不方便。通常Accesss資料庫放置在虛擬機器主機上,需要把它下載下來“壓縮修複”完後再傳上去很浪費時間,所以最好能線上對資料庫進行壓縮。

2.在線壓縮資料庫的實現

2.1.添加引用

在VS.Net環境的解決方案下添加引用。方法如下:項目→添加引用→選項卡→瀏覽(c:\program files\comm files\System\ado\msjro.dll)。

2.2.建立Web應用程式表單

在Web表單(DataBase.aspx)上放置一個按鈕:
<asp:Button ID="CompactBtn" runat="server" Text=" 壓縮資料庫 " OnClick="CompactBtn_Click" />
再添加一個Label控制項:
<asp:Label ID="MsgLabel" runat="server"></asp:Label>

2.3.代碼狀態下,添加引用

using System;
using System.IO;
using JRO;

2.4.添加代碼

//壓縮資料庫
protected void CompactBtn_Click(object sender, EventArgs e)
{
 string DbPath1, DbPath2, DbConn1, DbConn2;

 DbPath1 = Server.MapPath("../App_Data/DataBase.mdb");//原資料庫路徑
 DbPath2 = Server.MapPath("../App_Data/DataBase2.mdb");//壓縮後的資料庫路徑
 DbConn1 = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + DbPath1;
 DbConn2 = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + DbPath2;

 try
 {
  JetEngine DatabaseEngin = new JetEngine();
  DatabaseEngin.CompactDatabase(DbConn1, DbConn2);//壓縮

  File.Copy(DbPath2, DbPath1, true);//將壓縮後的資料庫覆蓋原資料庫
  File.Delete(DbPath2);//刪除壓縮後的資料庫

  MsgLabel.Text = "資料庫壓縮成功!";
 }
 catch
 {
  MsgLabel.Text = "資料庫壓縮失敗,請重試!";
 }
}

3.備份資料庫

3.1.建立Web應用程式表單

在Web表單(DataBase2.aspx)上放置一個按鈕:
<asp:Button ID="BackUpBtn" runat="server" Text=" 備份資料庫 " OnClick="BackUpBtn_Click" />
再添加一個Label控制項:
<asp:Label ID="MsgLabel" runat="server"></asp:Label>

3.2.代碼狀態下,添加引用

using System;
using System.IO;

3.3.添加代碼

//備份資料庫
protected void BackUpBtn_Click(object sender, EventArgs e)
{
 string DbPath1, DbPath2, DbName4DbPath2;

 DbName4DbPath2 = DateTime.Now.ToString().Replace(":",".");
 DbPath1 = Server.MapPath("../App_Data/DataBase.mdb");
 DbPath2 = Server.MapPath("../App_Data/" + DbName4DbPath2 + ".mdb");

 try
 {
  File.Copy(DbPath1, DbPath2, true);

  MsgLabel.Text = "Database Backup成功到" + DbName4DbPath2 + ".mdb!";
 }
 catch
 {
  MsgLabel.Text = "Database Backup失敗,請重試!";
  MsgLabel.CssClass = "redColor";
 }
}

4.總結

經過壓縮使Microsoft Access真正釋放佔據的多餘空間,資料庫盡量減小,保證它最有效地運行。因此,在設計的過程中,不可忽視對Microsoft Access進行壓縮的重要性。
建議壓縮前先對資料庫進行備份。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.