这两天,同学问我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地址即可。