unity2021连接sqlServer数据库(支持安卓)

unity2021连接数据库之前要先导入三个dll文件,不然打包时会报错。打开unity安装目录下面Editor\Data\MonoBleedingEdge\lib\mono文件夹。再打开文件夹unityaot-win32或者unityjit-win32也行,找到I18N.CJK.dll,I18N.dll,I18N.West.dll这三个文件导入到unity环境就配置好了。除此之外要确保api兼容级别设置成.NET Framework而不是.NET Standard2.1。设置方法是点击菜单编辑-项目设置-玩家,配置下面的api兼容级别。如图所示:

最后再写连接数据库代码,因为连接远程数据库比较耗时,如果直接用同步方式连接数据库容易卡死,我这里用多线程与协程简单写了一个数据库连接类SqlManage,代码如下:

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

public class SqlManage
{
    public readonly string SqlAddress = "server=数据库地址;database=数据库名;uid=用户名;pwd=密码";
    public SqlManage(string SqlAddress)
    {
        this.SqlAddress = SqlAddress;
    }
    public IEnumerator 获取数据(string sqlStr,  Action<DataTable> dataAction)
    {
       yield return 获取数据(sqlStr, SqlAddress, dataAction);
    }
    public static IEnumerator 获取数据(string sqlStr,string SqlAddress, Action<DataTable> dataAction)
    {
        
        DataSet ds = new DataSet();
        yield return 启动线程(() => {
            SqlDataAdapter sda = new SqlDataAdapter(sqlStr, SqlAddress);
            sda.Fill(ds);
        }, (string err) => {
            if (string.IsNullOrEmpty(err))
            {
                dataAction(ds.Tables[0]);
            }
            else
            {
                dataAction(null);
            }
        });
    }

    public static IEnumerator 启动线程(Action threadAction,Action<string> endAction = null)
    {
        string err = null;
        Thread thread = new Thread(() => {
            try
            {
                threadAction();
            }
            catch (Exception e)
            {
                err = e.Message;
                Debug.LogError("线程出错:"+err);
            }
        });
        thread.Start();
        if (endAction!=null)
        {
            yield return new WaitWhile(() => thread.IsAlive);
            endAction(err);
        }
    }
}

使用该类方法测试如下:

void Start(){
    SqlManage Sql = new SqlManage("server=数据库地址;database=数据库名;uid=用户名;pwd=密码");
        StartCoroutine(Sql.获取数据("select * from 表名", (DataTable table) => {
            foreach (DataRow row in table.Rows)
            {
                foreach (var item in row.ItemArray)
                {
                    Debug.Log(item);
                }
            }
        }));
}

 经过打包测试支持windos也支持安卓平台,但是不支持webgl,ios没测试不确定是否支持。

  • 15
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 11
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值