c# - 在Unity3d中使用MySQL,填充数据表

标签 c# mysql unity-game-engine

我尝试简单地填充数据表,但它会在特定时间内导致卡住并引发此异常:

连接尝试失败,因为连接方在一段时间后没有正确响应,或者建立的连接失败,因为连接的主机未能响应。

可能做错了什么,但如果没有错误,可能是在 Unity 方面

//open connection to database
private bool OpenConnection()
{
    try
    {
        connection.Open();
        return true;
    }
    catch (MySqlException ex)
    {
        //0: Cannot connect to server.
        //1045: Invalid user name and/or password.
        switch (ex.Number)
        {
            case 0:
                Debug.Log("Cannot connect to server.  Contact administrator");
                break;

            case 1045:
                Debug.Log("Invalid username/password, please try again");
                break;
        }
        Debug.Log("error : " + ex.Number + " | " + ex.Message);
        return false;
    }
}

//Close connection
private bool CloseConnection()
{
    try
    {
        connection.Close();
        return true;
    }
    catch (MySqlException ex)
    {
        Debug.Log(ex.Message);
        return false;
    }
}   

public DataTable SendQueryAndReceiveResult(string query)
{
    try
    {
        MySqlCommand cmd = new MySqlCommand(query, connection);
        MySqlDataAdapter adapter = new MySqlDataAdapter(cmd);
        DataTable dataTable = new DataTable();

        if (OpenConnection() == true)
        {
            adapter.Fill(dataTable);

            CloseConnection();
            Debug.Log("Succesfully send and receive the table from query : \n" + query);
            return dataTable;
        }
    }
    catch (System.Exception ex)
    {
        Debug.LogError("ERROR when sending and receiving the table from query : \n" + query);
        Debug.LogError(ex.Message);
        return null;
    }

    Debug.LogError("ERROR when sending and receiving the table from query : \n" + query);
    return null;
}

最佳答案

您无法在 Unity 内使用阻塞 IO MySQL C# 驱动程序,因为只有一个玩家线程。此外,您需要允许来自防火墙的连接。

首先使用非阻塞(异步)驱动程序,例如 this.

关于c# - 在Unity3d中使用MySQL,填充数据表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58565232/

相关文章:

php - 为什么PHP更新数据没有被选中?

c# - 统一,C# |如何在方法之间设置等待时间?

c# - 异步和调度程序解释

c# - 无法从共享点列表加载计算字段

c# - 我的 Regex.Replace 不起作用

mysql - 连接到服务器并执行多个命令

c# - 关于Entity Framework Context Lifetime的问题

来自命名查询的 MySQL 错误

animation - 当动画已使用 Unity2D Sprite 中的 Animator 添加到游戏对象时,无法翻译游戏对象

android - fontSize 在 Unity 中究竟意味着什么?