Unity連線Sql資料庫(PC端)
阿新 • • 發佈:2018-12-28
宣告:Unity版本:5.2.3f1,資料庫版本:SqlServer 2008
1.複製System.Data.Dll檔案到Unity工程中(與Unity的安裝路徑有關)
注意:複製後的檔案放在與你程式碼同級目錄即可
2. 新建一個用於連線資料庫的指令碼
新增以下引用:(如果引用後報錯,將Api Compatibility Level 改為.Net2.0)
using System.Data;
using System.Data.SqlClient;
using System; using UnityEngine; using System.Collections; using System.Data; using System.Data.SqlClient; using UnityEngine.UI; public class ConnectSQL : MonoBehaviour { public Text m_messageTex;//連線是否成功文字 public Text m_sqlInfoTex;//顯示讀取資料庫中的資訊 void Start() { //連線資料庫的字串(引數1:資料庫地址,引數2:資料庫名稱,引數3:使用者名稱,引數4:密碼) string tConnectStr = "server=127.0.0.1;database=MyDatabase;uid=sa;pwd=666"; //申請一個連線物件 SqlConnection tSqlConnection = new SqlConnection(tConnectStr); //如果關閉則開啟 if (tSqlConnection.State == ConnectionState.Closed) { tSqlConnection.Open(); } //讀取資料庫中的表資料 string tSqlStr = "select * from UserInfo Where Id = 13"; SqlCommand tSqlCommand = new SqlCommand(tSqlStr, tSqlConnection); //申請一個用於儲存讀取來的資料容器 SqlDataReader tSqlDataReader = null; try { //儲存所有讀來的資料 tSqlDataReader = tSqlCommand.ExecuteReader(); //一行一行讀取資料 while (tSqlDataReader.Read()) { m_sqlInfoTex.text = tSqlDataReader["Name"].ToString(); m_messageTex.text = "連線成功"; } } //丟擲異常 catch (Exception exception) { m_messageTex.text = "連線失敗"; throw new Exception(exception.Message); } finally { //關閉資料庫 tSqlConnection.Close(); //釋放資源 tSqlConnection.Dispose(); } } }
3.連線通訊後的顯示
此時我的資料庫UserInfo表如下:
將所讀取的資料顯示在UI上,如下: