Untiy如何连接SQLServer2008

目前使用的是unity5.4的版本和SQLserver2008.

首先为了测试在数据库里新建了一个名为11的数据库,里面建了一个表,名为student

Untiy如何连接SQLServer2008_第1张图片

随便填入一些内容,如下:

Untiy如何连接SQLServer2008_第2张图片

Untiy如何连接SQLServer2008_第3张图片

然后做unity这边的工作。

首先去unity的安装的目录里,如下路径里,例如:E:\Program Files\Unity\Editor\Data\Mono\lib\mono\unity。这个路径下找到system.data的dll文件。把他放到unity的assets文件夹里。

 

Untiy如何连接SQLServer2008_第4张图片

然后打开脚本,这个dll会自动引入VS的编辑器里。。。如果没有你就右键点击引用去手动添加该dll。

关于引用问题,我开始用的是vs2017的版本,这个地方一直是无法引用的,后来换了2019的企业版就解决了。

Untiy如何连接SQLServer2008_第5张图片

然后用下面的代码去连接和查询数据库。如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Data;
using System.Data.SqlClient;

public class sqltest : MonoBehaviour {
    //数据库连接的定义
    private SqlConnection sqlCon;
    //数据库连接地址
    private string sqlAddress = "server=192.168.239.10;database=11;uid=sa;pwd=123456";
    //适配器
    SqlDataAdapter sda = null;

    // Use this for initialization
    void Start()
    {
        //传建一个数据库连接事件
        sqlCon = new SqlConnection(sqlAddress);
    }

    // Update is called once per frame
    void Update()
    {
        //按下空格键,执行对应操作
        if (Input.GetKeyDown(KeyCode.Space))
        {
            Debug.Log("space down");
            try
            {
                //打开连接
                sqlCon.Open();
                //连接成功
                Debug.Log("Yes");
                //数据库操作语句
                string sql = "select * from student";
                ////数据库操作
                sda = new SqlDataAdapter(sql, sqlAddress);
                //结果集
                DataSet ds = new DataSet();
                //将查询的结果放入结果集
                sda.Fill(ds, "student");
                //打印结果
                 print(ds.Tables[0].Rows[0][0].ToString());
               
            }

            //如果出现异常,抛出
            catch (System.Exception)
            {
                Debug.Log("No");
                throw;
            }

        }
        //空格键抬起,数据库连接关闭
        else if (Input.GetKeyUp(KeyCode.Space))
        {
            Debug.Log("space up");
            sqlCon.Close();
        }
    }
}

 

然后测试,按下空格键,会看到log如下:查询到了表中第一行的第一列的名字。

Untiy如何连接SQLServer2008_第6张图片

你可能感兴趣的:(unity3D)