打开Visual Studio_视图_服务器资源管理器
在弹出的窗口,右键数据连接,选择添加连接
选择MySQL Database,点击继续
输入数据库地址、账号、密码、数据库名,然后点击测试连接
弹出对话框“测试连接成功”,则可进入下一步
在路径:C:\Program Files (x86)\MySQL\MySQL Connector Net6.8.7\Assemblies\v2.0中找到MySql.Data.dll导入Unity中Plugins文件夹下
对应Unity的安装目录:Unity\Editor\Data\MonoBleedingEdge\lib\mono\unityjit;找到其余dll文件
public void InquireMysql() { //数据库地址、用户名、密码、数据库名 string sqlSer = "server = localhost;port = 3306;database = test;user = root;password = 123456"; //建立连接 MySqlConnection conn = new MySqlConnection(sqlSer); try { conn.Open(); Debug.Log("------链接成功------"); //sql语句 string sqlQuary = " select * from mytable"; MySqlCommand comd = new MySqlCommand(sqlQuary, conn); MySqlDataReader reader = comd.ExecuteReader(); while (reader.Read()) { //通过reader获得数据库信息 Debug.Log(reader.GetString("user_name")); Debug.Log(reader.GetString("user_password")); } } catch (System.Exception e) { Debug.Log(e.Message); } finally { conn.Close(); } }
运行结果:
public void ChangedMysql() { //数据库地址、用户名、密码、数据库名 string sqlSer = "server = localhost;port = 3306;database = test;user = root;password = 123456"; MySqlConnection conn = new MySqlConnection(sqlSer); try { conn.Open(); Debug.Log("------链接成功------"); string sqlQuary = "insert into mytable(user_name,user_password) values (@user_name, @user_password)"; MySqlCommand comd = new MySqlCommand(sqlQuary, conn); comd.Parameters.AddWithValue("@user_name", "用户名"); comd.Parameters.AddWithValue("@user_password", "密码"); comd.ExecuteNonQuery(); } catch (System.Exception e) { Debug.Log(e.Message); } finally { conn.Close(); } }
运行结果:
路径:Project Setting->player->othersetting->Configuration->Api Compatibility Level