I have a problem with my Unity together with MySql, I need every 1 second to get data from the database, but when he opens the connection the game crashes.
Code:
void CheckVersion(){
MySqlConnection conn = new MySqlConnection(LinhaMySQL);
try
{
conn.Open();
string sql = "SELECT VERSION FROM servidor";
MySqlCommand cmd = new MySqlCommand(sql, conn);
object result = cmd.ExecuteScalar();
cmd.CommandTimeout = 0;
if (result != null)
{
MySqlDataReader reader = cmd.ExecuteReader();
while(reader.Read())
{
string versionserver = reader["VERSION"].ToString();
if(Application.version == versionserver) {
Debug.Log("Atualizado!");
} else {
if(LoginGUI.activeSelf == true) {
MessageShow("VersĂŁo desatualizada, atualize seu jogo.", "FECHAR");
//Debug.Log("Desatualizado!");
}
}
}
}
}
catch (Exception ex)
{
if(LoginGUI.activeSelf == true) {
MessageShow("NĂŁo foi possĂvel se conectar com o servidor!", "FECHAR");
}
}
conn.Close();
}
I haven’t used this method before, but from a quick glance, it looks like it may be something to do with using two execute commands.
@Kurt-Dekker is right and you should always try and use the async operations.
If the object is not null, you should just be able to just cast it to a string. And not have to do the second execution. So long as the field you want is of the first column. I may be wrong though, have not used this way before.
You could use Visual Studio to debug, enter a breakpoint at the start of the function, and step through until you find what causes the crash.
Also, just an option… I would recommend using Dapper for any Databasing work when ADO/EF6 is not an option.
I personally like Dapp-Contrib as I started out with ADO. But there are several options to choose from. https://dapper-tutorial.net/dapper
Additionally you should pool the connection and not reconnect every second. Perhaps try to call only once the method CheckVersion() in a Unity start() method and check by the debugger whats going on.
To be honest, just do not connect to MySQL from Unity applications ever, unless you’re developing some in-house simulator of some sort.
If you’re planning to distribute your application, connecting to a central database is extremely dangerous this way. If you need a central DB, put a layer (PHP or Python or whatever) between the two and just call REST endpoints.
If you want a local database, MySQL is too heavy for a game-like application, you are better off with some NoSQL lightweight solution.
@ is spot on, but I kinda assumed you were connecting to a database built into your app, which of course necessitates putting it in StreamingAssets, and on certain targets (like Android) requires you to copy it OUT of your StreamingAssets and into a local temporary file for opening.