在使用 C# 開發 Windows Forms 應用程式時,若需連接 Access 資料庫(.accdb 格式),常會遇到「未在本地電腦上註冊 ‘Microsoft.Jet.OLEDB.12.0’ 提供程式」的錯誤。即使安裝了 AccessDatabaseEngine.exe,問題仍可能持續存在。
程式碼中使用的連接字串採用 provider=Microsoft.Jet.OLEDB.12.0,但 Jet OLEDB 最高版本僅到 4.0。對於 Access 2007 及以上版本(.accdb),必須改用 ACE (Access Database Engine) 提供程式,版本號為 12.0 或 14.0 以上。
// 針對 .accdb 檔案
string connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strPath + ";Persist Security Info=False;";
// 或使用 14.0/15.0/16.0 視安裝版本而定
private void btn_login_Click(object sender, EventArgs e)
{
if (!judge())
{
MessageBox.Show("請輸入正確的帳號密碼...");
return;
}
string strPath = Application.StartupPath + "\\login.accdb";
// 使用 ACE 提供程式
string connStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + strPath;
using (OleDbConnection conn = new OleDbConnection(connStr))
{
try
{
conn.Open();
string sql = "SELECT UserId, Password FROM [user] WHERE UserId=@uid AND Password=@pwd";
using (OleDbCommand cmd = new OleDbCommand(sql, conn))
{
cmd.Parameters.AddWithValue("@uid", txt_username.Text);
cmd.Parameters.AddWithValue("@pwd", txt_password.Text);
using (OleDbDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
username = txt_username.Text;
password = txt_password.Text;
MessageBox.Show("登入成功!");
Form f2 = new Form2();
this.Hide();
f2.ShowDialog();
this.Dispose();
}
else
{
MessageBox.Show("帳號或密碼錯誤");
}
}
}
}
catch (Exception ex)
{
MessageBox.Show("資料庫連接失敗:" + ex.Message);
}
}
}
using 區塊自動釋放資源。依照上述方式修正連接字串與程式碼結構,即可解決提供程式未註冊的問題,並提升程式的安全性與穩定性。