简体   繁体   中英

Using MySQL in Unity3d, Fill datatable

I trying to simply fill a datatable but it cause freeze during a certain time and throw this exception:

A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.

Probably doing something wrong, but if there's no error maybe it's on Unity side

//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;
}

You cannot use the blocking IO MySQL C# driver inside Unity, because there is only one player thread. Additionally, you will need to allow connections from your firewall.

Start by using a non-blocking (async) driver like this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM