標籤:
這兩天,同學問我Unity3d串連SQL Server的問題,當時我只是簡單的說:“應該一樣吧,就是那簡單的幾句啊”。之後他讓我試了下,我才發現有問題了。故此寫下一篇部落格,要牢記這件事的教訓,操作資料庫,我們人人都會,然而,我們要知道:有些事,並不是我們會啦,就有能力去完成的,我們必須要注重各種細節,才能勝任我們作為程式員的工作(雖然我還是個學生)。
下面進入主題吧,我們先看看串連資料庫:
1、引入程式集System.Data.dll,位置在C:\Program Files\Unity\Editor\Data\Mono\lib\mono\unity(預設位置),把System.Data.dll檔案複製到當前Unity專案檔下,即Assets檔案夾下就可以了。
2、將程式集Sysem.Data.dll用VS2015手動引入即可。
using UnityEngine;using System.Collections;using System.Data.SqlClient;using System;public class Testaa : MonoBehaviour{ // Use this for initialization SqlConnection con = new SqlConnection("Data Source=主機名稱;Initial Catalog=db_CSharp;Persist Security Info=True;User ID=sa;Password=密碼"); void Start() { Do(); } void Do() { con.Open(); SqlCommand com = new SqlCommand("select * from tb_PDic", con); SqlDataReader sdr = null; try { sdr = com.ExecuteReader(); print("名稱\t\t\t\t價格\n"); while (sdr.Read()) { print(sdr["Name"] + "\t\t\t\t" + sdr["Money"] + "\n"); } con.Close(); } catch (Exception ex) { print(ex.Message); } } // Update is called once per frame void Update() { }}
儲存後運行。出現如下錯誤:
SocketException: 使用了與請求的協議不相容的地址。
System.Net.Sockets.Socket.Connect (System.Net.EndPoint remoteEP, Boolean requireSocketPolicy)
System.Net.Sockets.Socket+Worker.Connect ()
Rethrow as TdsInternalException: Server does not exist or connection refused.
Mono.Data.Tds.Protocol.TdsComm..ctor (System.String dataSource, Int32 port, Int32 packetSize, Int32 timeout, TdsVersion tdsVersion)
Mono.Data.Tds.Protocol.Tds..ctor (System.String dataSource, Int32 port, Int32 packetSize, Int32 timeout, TdsVersion tdsVersion)
Mono.Data.Tds.Protocol.Tds70..ctor (System.String server, Int32 port, Int32 packetSize, Int32 timeout, TdsVersion version)
Mono.Data.Tds.Protocol.Tds80..ctor (System.String server, Int32 port, Int32 packetSize, Int32 timeout)
Mono.Data.Tds.Protocol.TdsConnectionPoolManager.CreateConnection (Mono.Data.Tds.Protocol.TdsConnectionInfo info)
Mono.Data.Tds.Protocol.TdsConnectionPool.GetConnection ()
System.Data.SqlClient.SqlConnection.Open ()
Rethrow as SqlException: Server does not exist or connection refused.
System.Data.SqlClient.SqlConnection.Open ()
(wrapper remoting-invoke-with-check) System.Data.SqlClient.SqlConnection:Open ()
Testaa.Do () (at Assets/Testaa.cs:17)
Testaa.Start () (at Assets/Testaa.cs:13)
解決方案:將主機名稱改為主機的IP地址即可。
Unity3d串連SQL Server資料庫出現SocketException: 使用了與請求的協議不相容的地址錯誤