Visual C# 作為微軟主推的新一代開發語言,其資料庫處理能力是核心優勢之一。透過 .NET Framework SDK 中的 System.Data.OleDb 命名空間,C# 可統一存取各類資料庫。本文將透過兩個實例,分別示範存取本地 Access 2000 與遠端 SQL Server 7.0 資料庫的完整流程。
my.mdb)所有資料庫操作遵循統一的五步驟:
using System;
using System.Data.OleDb;
using System.Windows.Forms; // 需用 Application.StartupPath
string strConnect = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
Application.StartupPath + "\\my.mdb";
OleDbConnection conn = new OleDbConnection(strConnect);
Provider:指定 OLE DB 提供者(Access 使用 Jet 4.0)Data Source:資料庫檔案完整路徑OleDbCommand cmd = new OleDbCommand("SELECT * FROM Persons", conn);
try
{
conn.Open();
OleDbDataReader reader = cmd.ExecuteReader();
Console.WriteLine("資料集第一欄位內容:");
while (reader.Read())
{
Console.WriteLine(reader.GetString(0)); // 讀取第一欄位
}
reader.Close();
conn.Close();
}
catch (OleDbException ex)
{
Console.WriteLine("錯誤:" + ex.Errors[0].Message);
}
| 類別 | 用途 |
|---|---|
| OleDbConnection | 管理資料庫連線 |
| OleDbCommand | 封裝 SQL 指令 |
| OleDbDataReader | 唯讀、順向資料流讀取器 |
| OleDbException | 資料庫錯誤處理 |
下一篇將詳細說明:
first.cs 原始碼