当前在做的一个Unity项目需要连接到MySQL数据库,弄了一整天,排了很多错,终于在Unity上成功连接到MySQL数据库了,所以分享一下,避免有这个需求的朋友不用花那么多时间。
我使用的软件是 Unity20184.0f1 + mysql-8.0.24
导入 MySql.Data.dll
首先需要把 MySql.Data.dll 导入到Assets/Plugins
这个dll需要安装Connector/NET,在安装目录\Assemblies\v4.0中
拿到,最好不要下载版本太高的,版本太高导入的时候会报错,我下的是6.9.9,或者可以在下面的连接直接下载MySql.Data.dll文件导入到文件夹中。
链接: https://pan.baidu.com/s/1IgNQ8w0RUni2Ga-eEQlfIg
提取码: j31r
如果是低版本的Unity的话,可能还需要导入System.Data.dll、System.Drawing.dll,至于从哪个版本开始需要导入这两个文件的话,我也不是很清楚,你可以在visual studio打开项目看一下这两个引用是否包含在里面,如果没有的话,就需要导入这两个dll,这两个dll的路径为: Unity的安装目录\Editor\Data\Mono\lib\mono\2.0
连接mysql数据库
建立一个数据库连接类SqlAccess.cs
using System;
using System.Data;
using MySql.Data.MySqlClient;
using UnityEngine;
using System.Text;
public class SqlAccess
{
public static MySqlConnection dbConnection;
//如果只是在本地的话,写localhost就可以。
// static string host = "localhost";
//如果是局域网,那么写上本机的局域网IP
static string host = "localhost";
static string port = "3306";
static string username = "root";
static string pwd = "123456";
static string database = "db_blessing";
public SqlAccess()
{
OpenSql();
}
/// <summary>
/// 连接数据库
/// </summary>
public static void OpenSql()
{
try
{
string connectionString = string.Format("server = {0};port={1};database = {2};user = {3};password = {4};", host, port, database, username, pwd);
Debug.Log(connectionString);
dbConnection = new MySqlConnection(connectionString);
dbConnection.Open();
Debug.Log("建立连接");
}
catch (Exception e)
{
throw new Exception("服务器连接失败,请重新检查是否打开MySql服务。" + e.Message.ToString());
}
}
/// <summary>
/// 关闭数据库连接
/// </summary>
public void Close()
{
if (dbConnection != null)
{
dbConnection.Close();
dbConnection.Dispose();
dbConnection = null;
}
}
/// <summary>
/// 查询
/// </summary>
/// <param name="tableName">表名</param>
/// <param name="items"></param>
/// <param name="col">字段名</param>
/// <param name="operation">运算符</param>
/// <param name="values">字段值</param>
/// <returns>DataSet</returns>
public DataSet SelectWhere(string tableName, string[] items, string[] col, string[] operation, string[] values)
{
if (col.Length != operation.Length || operation.Length != values.Length)
throw new Exception("col.Length != operation.Length != values.Length");
StringBuilder query = new StringBuilder();
query.Append("SELECT ");
query.Append(items[0]);
for (int i = 1; i < items.Length; ++i)
{
query.Append(", ");
query.Append(items[i]);
}
query.Append(" FROM ");
query.Append(tableName);
query.Append(" WHERE 1=1");
for (int i = 0; i < col.Length; ++i)
{
query.Append(" AND ");
query.Append(col[i]);
query.Append(operation[i]);
query.Append("'");
query.Append(values[0]);
query.Append("' ");
}
Debug.Log(query.ToString());
return ExecuteQuery(query.ToString());
}
/// <summary>
/// 执行sql语句
/// </summary>
/// <param name="sqlString">sql语句</param>
/// <returns></returns>
public static DataSet ExecuteQuery(string sqlString)
{
if (dbConnection.State == ConnectionState.Open)
{
DataSet ds = new DataSet();
try
{
MySqlDataAdapter da = new MySqlDataAdapter(sqlString, dbConnection);
da.Fill(ds);
}
catch (Exception ee)
{
throw new Exception("SQL:" + sqlString + "/n" + ee.Message.ToString());
}
finally
{
}
return ds;
}
return null;
}
}
测试数据库类TestSql .cs
using System.Data;
using UnityEngine;
public class TestSql : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
SqlAccess sql = new SqlAccess();
string[] items = { "id", "bless", "state", "time", "name", "banji" };
string[] col = { };
string[] op = { };
string[] val = { };
DataSet ds = sql.SelectWhere("blessings", items, col, op, val);
if(ds != null)
{
DataTable table = ds.Tables[0];
foreach (DataRow row in table.Rows)
{
string str = "";
foreach (DataColumn column in table.Columns)
str += row[column] + " ";
Debug.Log(str);
}
}
}
}
在Unity中创建一个空的GameObject,把TestSql .cs脚本挂上,点击 Play 运行就可以了。
报错
一旦运行后,会报出一个错误:
Authentication method ‘caching_sha2_password’ is not supported.
因为最新的数据库更改了加密方式,mysql8.0以后的版本从原来的 mysql_native_password 更改为 caching_sha2_password
我们需要改回去,不然会报上面的错误。
修改方法:
修改账户的加密方式
需要进入到mysql数据库中
查看User表中,你使用的用户的加密方式是不是 caching_sha2_password,若是的话按如下操作。
上面使用到的sql语句
# 显示数据库
show databases;
# 使用mysql数据库
use mysql;
# 查询mysql数据库中user表plugin列的值
select User, plugin,authentication_string from user;
# 修改加密规则
ALTER USER 'root'@'localhost' IDENTIFIED BY 'password' PASSWORD EXPIRE NEVER;
# 更新一下用户的密码
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';
# 刷新权限
FLUSH PRIVILEGES;
# 再重置下密码
alter user 'root'@'localhost' identified by '123456';
# 查看加密方式是否改回mysql_native_password
select User, plugin,authentication_string from user;
修改配置文件
在mysql安装目录下打开my.ini
,添加下面的一句话到[mysqld]
下面
default_authentication_plugin=mysql_native_password
用管理员权限打开命令窗口,重启mysql服务
net stop mysql
net start mysql
效果
发布成PC端连接不上mysql
项目完成后进行打包,结果发现连接不上mysql,这时需要添加三个dll,他们在unity安装目录的 Editor\Data\Mono\lib\mono\2.0
同时在player setting里设置,把api compatibility level 改为.NET 4.x