You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity打包后用System.Data.SqlClient遇InvalidProgramException问题求助

Unity打包桌面版后SQL Server数据库连接异常解决方案

问题背景

Unity编辑器内使用System.Data.SqlClient访问SQL Server一切正常,但打包桌面版本后出现连锁异常:

  • 初始报错:NotSupportedException: Encoding 1252 data could not be found
  • 添加I18N.dll和I18N.West.dll到Assets目录后,又触发InvalidProgramException: Invalid IL code in I18N.Common.Manager
  • 尝试从unityaot-win32目录复制对应DLL、添加链接XML文件均未解决,核心问题指向System.Data.SqlClient的兼容性。

解决方案

1. 替换为官方推荐的Microsoft.Data.SqlClient

System.Data.SqlClient已被微软标记为旧版,Microsoft.Data.SqlClient是其替代方案,对Unity的AOT编译兼容性更好:

  • 操作步骤:
    1. 在Unity的Package Manager中,通过NuGet安装Microsoft.Data.SqlClient(需确保版本与Unity的.NET Runtime匹配,推荐.NET 4.x版本);
    2. 将代码中的命名空间从using System.Data.SqlClient;替换为using Microsoft.Data.SqlClient;,业务逻辑无需大幅修改。

2. 修复System.Data.SqlClient的AOT与链接器配置

如果坚持使用旧版库,需修正以下配置:

  • 调整链接器XML:移除无关的GeometryGymIFC,保留必要程序集的完整引用:
    <linker>
      <assembly fullname="System.Data.SqlClient" preserve="all"/>
      <assembly fullname="I18N" preserve="all"/>
      <assembly fullname="I18N.West" preserve="all"/>
    </linker>
    
  • 正确放置DLL:从Unity安装目录的Editor\Data\MonoBleedingEdge\lib\mono\unityaot-win32下复制I18N.dll和I18N.West.dll,粘贴到Assets/Plugins目录(而非Assets根目录),确保DLL版本与Unity的AOT环境匹配。

3. 编码与运行时配置优化

  • 在Unity Player Settings中,将Scripting Runtime Version设置为.NET 4.x Equivalent,提升兼容性;
  • 连接字符串中显式添加编码相关配置,避免自动编码检测出错:
    connectString.CurrentLanguage = "us_english";
    connectString.Encrypt = false; // 根据实际环境调整
    

4. 打包调试技巧

  • 打包时勾选Development Build和Script Debugging,获取更详细的错误日志,定位具体异常节点;
  • 确保打包后的程序运行用户拥有SQL Server的访问权限(使用集成安全时尤为重要)。

修改后示例代码(使用Microsoft.Data.SqlClient)

using Microsoft.Data.SqlClient;
using UnityEngine;

public class DBConnector : MonoBehaviour
{
    void Start()
    {
        SqlConnectionStringBuilder connectString = new SqlConnectionStringBuilder();
        connectString.DataSource = "SampleSource";
        connectString.InitialCatalog = "TestSource";
        connectString.IntegratedSecurity = true;
        // 补充配置避免编码与连接超时问题
        connectString.ConnectTimeout = 30;
        connectString.CurrentLanguage = "us_english";

        using (SqlConnection sqlConn = new SqlConnection(connectString.ConnectionString))
        {
            try
            {
                sqlConn.Open();
                Debug.Log("数据库连接成功");
            }
            catch (SqlException e)
            {
                Debug.LogError($"数据库连接失败:{e.Message}");
            }
        }
    }
}

内容的提问来源于stack exchange,提问作者Myosotis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.05 16:42:21