首页 > 解决方案 > Unity3d中使用MySQL,填充数据表

问题描述

我试图简单地填充数据表,但它会在特定时间内导致冻结并抛出此异常:

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

可能做错了什么,但如果没有错误,可能是在 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;
}

标签: c#mysqlunity3d

解决方案


您不能在 Unity 中使用阻塞 IO MySQL C# 驱动程序,因为只有一个播放器线程。此外,您需要允许来自防火墙的连接。

首先使用像这样的非阻塞(异步)驱动程序


推荐阅读