In this short tutorial, I’m going to explain how you can add MySQL capabilities to your Unity application. This will allow you to connect to a MySQL database from your application and fill the database with some data (e.g. users’ scores). To do so, you first of all need to obtain a MySQL Connector. Not every version of the Connector, however, will work with Unity. To obtain the Connector do the following steps:
- Go to https://dev.mysql.com/downloads/connector/net/
- Click on the “Looking for previous GA?” link.
- Select Version: 6.7.9 (This is the last version that contains the library compiled with the .Net 2.0 Framework)
- Select Platform: .Net & Mono
- Click on the “Download” button.
- Extract the files to a directory of your choice.
Next, we will create a new database schema with a table that can store string values. You can do this using MySQL Workbench.
- Open MySQL Workbench
- Connect to the local database.
- Create a new schema in the connected server and call it unity.
- Set unity schema as default schema by clicking on it with the right mouse button and selecting “Set as Default Schema”.
- Create a new table in the unity schema, call it scores, and define 3 columns: idscores as INT, playername as VARCHAR(45), and playscore as INT.
- Set the following flags for the idscores column: Primary Key, Not Null, and Auto Increment.
- Set the following flag for the columns playername and playerscore: Not Null.
Now we need a new user who will have privileges to write in and read from the unity schema.
- Click, in the navigator panel of the MySQL Workbench, on the User and Privileges link.
- Click on the button “Add Account”.
- Define a username of your choice.
- Leave Authentification Type as Standard (I had a problem to connect to the DB from a Linux machine while using other Authentification Type)
- Leave Limit to Hosts Matching as %. This will allow you to connect from any machine.
- Define a password of your choice.
- Leave Account Limits and Administrative Roles settings unchanged.
- On the Schema Privileges panel click on the button “Add Entry…”.
- Activate the option “Selected schema”, select the unity schema, and click on “Ok”.
- Next, provide the object rights: SELECT and INSERT for the entry and click on “Apply”.
Finally, we will write a small Unity application that will connect to a MySQL database and write a test-string into a table.
- Create a new Unity project
- Drag-and-Drop the MySQL.Data.dll file into the Assets folder (You are interested in the library that lies in the v2.0 directory)
- Next, you have to copy the System.Data.dll file into the Assets folder. If you work on Windows, then you can find the file in C:\Program Files\Unity\Editor\Data\Mono\lib\mono\2.0
- Finally, create a new C# script and put the following code into it:
using UnityEngine;
using MySql.Data.MySqlClient;
public class testSQL : MonoBehaviour {
MySqlConnection connection;
// Use this for initialization
void Start () {
SetupSQLConnection();
TestDB();
CloseSQLConnection();
}
private void SetupSQLConnection() {
if (connection == null) {
string connectionString = "SERVER=xxx.xxx.xxx.xxx;" + "DATABASE=unity;" + "UID=unityuser;" + "PASSWORD=yourpassword;";
try {
connection = new MySqlConnection(connectionString);
connection.Open();
} catch (MySqlException ex) {
Debug.LogError("MySQL Error: " + ex.ToString());
}
}
}
private void CloseSQLConnection() {
if (connection != null) {
connection.Close();
}
}
public void TestDB() {
string commandText = string.Format("INSERT INTO scores (playername, playerscore) VALUES ({0}, {1})", "'megaplayer'", 10);
if (connection != null) {
MySqlCommand command = connection.CreateCommand();
command.CommandText = commandText;
try {
command.ExecuteNonQuery();
} catch (System.Exception ex) {
Debug.LogError("MySQL error: " + ex.ToString());
}
}
}
}
Add an empty GameObject to your scene and put the script on it. Now each time you start the game a new entry will be added to your database. You can check it in the MySQL Workbench by clicking with the right mouse button on the table, selecting “Select Rows – Limit 1000”, and clicking in the appeared window on the lightning symbol.
Hi, thanks for your tutorial. I have error when trying to use MySQL.Data namespace.
I’m using unity 2017.2 and DbConnector 4.5 from MySQL. When importing MySQL.Data.dll I have incompatible error between target framework (4.x) and editor version so I have to exclude editor.
Do you have any ideas? I really don’t know anything about MySQL nor DB connector, but trying to make my demo app to work on this basis.
Thanks again.
probably You are using too new version of MySQL Connector/NET . Try to use ver 6.7.9 (https://downloads.mysql.com/archives/c-net/ ) or lower … as wirtten in the tutorial
Oracle doesn’t support the MySQL.dll that targets framework 2.0 anymore. If you use a more recent version, you have to change the settings of your unity:
Edit -> Project Settings -> Player -> Scripting Runtime Version
to experimental (.net 4.6 equivalent)
thanks Anton, btw.
Thanks to this tutorial, my connection between Unity application and MySql server works fine . Thanks !
hello, thanks for the tutorial.
everything works great in unity itself, only if I export it as webgl, the game does not connect to the server.
it only shows the following:
Rethrow as TypeInitializationException: The type initializer for ‘MySql.Data.MySqlClient.MySqlConfiguration’ threw an exception.
UnityLoader.js: 4
UnityLoader.js: 4 Rethrow as TypeInitializationException: The type initializer for ‘MySql.Data.MySqlClient.Replication.ReplicationManager’ threw an exception.
InvalidOperationException: Connection must be valid and open.
UnityLoader.js: 4 at MySql.Data.MySqlClient.ExceptionInterceptor.Throw (System.Exception exception) [0x00000] in : 0
Maybe you know why?
mysql.data.mysqlclient.DLL
.NET 4
MONO—->if setting to IL2CPP an install to android device can’t access
BUILD ANDROID
its work
In the editor everything is perfect, but when I build it does not connect to the data base 🙁
https://forum.unity.com/threads/notsupportedexception-encoding-1252-data-could-not-be-found-2020-2-3-f1.1058102/
That solve my problem 🙂 .