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

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

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

10-11 05:14