C# Builder 專業版內建 Borland Data Providers (BDP) 支援 DB2、InterBase、Oracle、SQL Server 等;Personal 版不含 BDP,僅能使用 .NET Framework 內建的 System.Data.SqlClient (SQL Server/MSDE) 或 System.Data.OleDb 進行最基礎的 ADO.NET 開發。
SqlConnection (命名 sqlConnection1)ConnectionString:
Data Source=.;Initial Catalog=master;Integrated Security=SSPI
master 為 MSDE 內建系統資料庫;實務上請改用自建資料庫。
private void button1_Click(object sender, EventArgs e)
{
try
{
sqlConnection1.ConnectionString = "Data Source=.;Initial Catalog=master;Integrated Security=SSPI";
sqlConnection1.Open();
MessageBox.Show("連線成功!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message); // 常見錯誤:MSDE 未啟動、連線字串錯誤、權限不足
}
}
此步驟最易失敗,請確認 SQL Server/MSDE 服務已啟動、連線字串正確、防火牆允許 1433 埠。
拖曳 SqlCommand (命名 sqlCommand1) → 設定 Connection = sqlConnection1 → 程式碼控制 CommandText 執行多條 SQL:
private void button2_Click(object sender, EventArgs e)
{
try
{
sqlCommand1.Connection = sqlConnection1;
// 1. 刪除舊表 (若不存在會擲出例外,用空 catch 忽略)
sqlCommand1.CommandText = "drop table test42";
try { sqlCommand1.ExecuteNonQuery(); } catch { }
// 2. 建立新表
sqlCommand1.CommandText = "create table test42 (id int NOT NULL, name nvarchar(42))";
sqlCommand1.ExecuteNonQuery();
// 3. 插入三筆測試資料
sqlCommand1.CommandText = "insert into test42 values(1, N'Bob Swart')";
sqlCommand1.ExecuteNonQuery();
sqlCommand1.CommandText = "insert into test42 values(2, N'Erik Mark Pascal Swart')";
sqlCommand1.ExecuteNonQuery();
sqlCommand1.CommandText = "insert into test42 values(3, N'Natasha Louise Delphine Swart')";
sqlCommand1.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
ExecuteNonQuery():執行不傳回資料列的 SQL (DDL、INSERT、UPDATE、DELETE),回傳影響列數。N:nvarchar 儲存 Unicode,SQL 字串常數需加 N'...' 避免編碼問題。Connection 屬性技巧:屬性值欄位雙擊或輸入首字母快速選取元件名稱。下一篇將示範 SqlDataAdapter、DataSet、DataGrid 完成資料查詢與顯示。