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数据库(支持安卓)
发布评论