Unity 專案預設不包含 ADO.NET 組件,需手動引用。
路徑視 Unity 安裝位置而定,典型路徑:
C:\Program Files\Unity\Hub\Editor\<版本>\Editor\Data\Mono\lib\mono\unity\System.Data.dll
# 或舊版路徑
C:\Program Files\Unity\Editor\Data\Mono\lib\mono\unity\System.Data.dll

Assets/
└── Plugins/ # 建議放在 Plugins 資料夾確保優先載入
└── System.Data.dll
專案右鍵 → 加入參考 → 瀏覽 → 選擇上述 System.Data.dll。


using System;
using System.Data;
using System.Data.SqlClient;
public class SqlTest : MonoBehaviour
{
private SqlConnection _conn;
private SqlDataAdapter _adapter;
void Start()
{
// 連線字串:必須使用 SQL Server 驗證 (sa/密碼),Windows 驗證在 Unity 中不支援
string connStr = @"Server=127.0.0.1;Database=ConnectTest;User ID=sa;Password=123456;";
_conn = new SqlConnection(connStr);
try
{
_conn.Open();
Debug.Log("資料庫連線成功!");
string sql = "SELECT * FROM Table1";
_adapter = new SqlDataAdapter(sql, _conn);
DataSet ds = new DataSet();
_adapter.Fill(ds, "Table1");
if (ds.Tables["Table1"].Rows.Count > 0)
{
var firstCell = ds.Tables["Table1"].Rows[0][0];
Debug.Log($"第一行第一欄值: {firstCell}");
}
}
catch (Exception ex)
{
Debug.LogError($"資料庫操作失敗: {ex.Message}");
}
}
void OnDestroy()
{
_adapter?.Dispose();
_conn?.Close();
_conn?.Dispose();
}
}

| 議題 | 建議方案 |
|---|---|
| 連線池 | 連線字串加 Pooling=true;Min Pool Size=1;Max Pool Size=100; (預設開啟) |
| 參數化查詢 | 杜絕 SQL 注入:cmd.Parameters.AddWithValue("@id", id) |
| 非同步操作 | 使用 await _conn.OpenAsync(), await reader.ReadAsync() 避免卡主執行緒 |
| 連線字串管理 | 存放於 Resources/connection.json 或 ScriptableObject,勿硬編碼 |
| 錯誤處理與重試 | Polly 套件實現指數退避重試 |
| 跨平台 (IL2CPP) | 確保 link.xml 保留 System.Data 命名空間,避免裁剪 |
| 替代方案 | 考慮 Entity Framework Core (需 .NET Standard 2.0+)、Dapper (輕量 ORM)、或 REST API + HttpClient 解耦資料庫 |
| 錯誤 | 原因 | 解決 |
|---|---|---|
| TypeLoadException: System.Data.SqlClient | 缺少 System.Data.dll 或版本不匹配 | 確認 DLL 放入 Plugins、Unity 版本對應 .NET 版本 |
| Login failed for user | SQL Server 未啟用混合驗證 / sa 密碼錯誤 | SSMS → 伺服器屬性 → 安全性 → SQL Server 和 Windows 驗證模式 → 重啟服務 |
| Connection timeout | 防火牆、IP 錯誤、SQL Browser 服務未啟動 (命名實例) | 開放 1433/動態埠、啟用 SQL Browser、檢查連線字串 Server 名稱 |
| IL2CPP 裁剪導致缺少型別 | Strip Level 高 | 建立 Assets/link.xml 保留 System.Data, System.Data.SqlClient |