admin管理员组文章数量:1794759
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没测试不确定是否支持。
版权声明:本文标题:unity2021连接sqlServer数据库(支持安卓) 内容由林淑君副主任自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.xiehuijuan.com/baike/1686658680a91565.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论