UnityDemo版本
Unity版本:2020.3.25;
Visual Studio版本: 2019;MySql.Data.dll版本:5.2.3
MySql版本:5.7.35
Mysql下载地址教程
Mysql下载地址
下载完成后解压到任意盘即可(楼主我选择的是D盘) 点击查看 勾选文件扩展名 右键新建文本文档 修改名称My.ini 修改后
打开my.ini 把以下文本复制到里面去 设置basedir(你的安装目录) 和datadir(数据库存放路径 注意:定义路径一定要有data文件夹)
[mysqld]
# 设置3306端口
port=3306
# 设置mysql的安装目录 ----------是你的文件路径-------------
basedir=D:\mysql-5.7.35-winx64
# 设置mysql数据库的数据的存放目录 ---------是你的文件路径data文件夹自行创建
datadir=D:\MysqlData\data
# 允许最大连接数
max_connections=200
# 允许连接失败的次数。
max_connect_errors=10
# 服务端使用的字符集默认为utf8mb4
character-set-server=utf8mb4
# 创建新表时将使用的默认存储引擎
default-storage-engine=INNODB
# 默认使用“mysql_native_password”插件认证
#mysql_native_password
default_authentication_plugin=mysql_native_password
[mysql]
# 设置mysql客户端默认字符集
default-character-set=utf8mb4
[client]
# 设置mysql客户端连接服务端时默认使用的端口
port=3306
default-character-set=utf8mb4
按下Win+R 输入cmd 然后回车 右键点击命令提示符 左键点击以管理员运行
先输入D: 回车 然后输入 cd 解压出来bin文件路径 然后在控制台输入指令
mysqld --install
如上图代表成功
接下来在控制台输入命令
mysqld --initialize --console
记下你随机出来密码 楼主随机出来密码是 VPWuVnRro3:)
输入以下指令启动Mysql服务器
net start mysql
如上图表示成功
登录Mysql服务器输入
mysql -u root -p
上图输入你的随机密码 楼主随机出来密码是 VPWuVnRro3:) 如上图显示就成功了
登录成功可以修改密码为123456 输入指令
ALTER USER 'root'@'localhost' IDENTIFIED BY '123456';
如上图成功
安装完成在控制台 输入quit和exit 退出
exit
接下来进行环境搭配 此电脑右键->属性->高级系统设置 新建系统变量
变量名为:MYSQL_HOME 变量值为你的MySQL安装路径 点击确定 找到path进行编辑 新建环境变量 变量为:%MYSQL_HOME%\bin
%MYSQL_HOME%\bin
在桌面找到此电脑右键此电脑->管理->服务与应用程序->服务
找到mysql->右键属性 将启动类型改为手动(防止开机速度变慢)
以上操作已经完成Mysql环境搭建 每次开机以管理员方法打开控制台输入命令
net start mysql
Navicat可视化窗口下载教程
下载地址 提取码: qy8s
安装教程
使用Navicat可视化窗口
点击连接
在点击mysql 最后弹出以下窗口 点击高级 自定义设置位置
然后点击确定 连接成功如下图 打开数据库出现以下界面 最后点击保存 弹出以下图
Mysql.data.dll下载地址
下载地址 提取码: wr2g
本次Demo下载地址
下载地址
网盘下载地址 提取码: 18gd
下载好后直接把资源包直接放进Assets文件中 运行如下环境配置成功 如果下载地址丢失请看下面
1:导入Unity安装目录下的必要程序集、I18N.CJK、I18N、I18N.West;(因为2020版的Unity默认加载了System.Data.dll,System.Drawing.dll,所以不用再次导入)安装目录路劲为:Editor\Data\MonoBleedingEdge\lib\mono\unityjit (注意一定是这个目录下的几个程序集,其他的尝试后无效并且报错) 在Unity Assets 新建Plugins文件 把这三个文件夹 放到里面去 最后在把Mysql.data.dll 也放进去图下 本项目脚本 SqlHelper
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using MySql.Data.MySqlClient;
using UnityEngine;
public class SqlHelper
{
string _server, _port, _user, _password, _datename, _format;
string connectStr;
MySqlConnection conn;
public SqlHelper(string host, string port, string user, string passwd, string database, string format = "utf8")
{
Connect(host,port,user,passwd,database,format);
}
public void Connect(string host, string port, string user, string passwd, string database, string format = "utf8")
{
_server = host;
_port = port; _user = user;
_password = passwd;
_datename = database;
_format = format;
connectStr = string.Format("server={0};port={1};user={2};password={3}; database={4};charset={5}", _server, _port, _user, _password, _datename, _format);
conn = new MySqlConnection(connectStr);
}
public void Open()
{
conn.Open();
}
public void Close()
{
conn.Close();
}
#region 查询语句
public DataSet Select(string tableName, string[] items)
{
string query = "SELECT " + items[0];
for (int i = 1; i < items.Length; ++i)
{
query += ", " + items[i];
}
query += " FROM " + tableName;
Debug.LogFormat("query: {0}", query);
return ExecuteQuery(query);
}
public DataSet Select(string tableName)
{
string query = "SELECT * FROM " + tableName;
return ExecuteQuery(query);
}
public DataSet SelectWhere(string tableName, string[] items, string[] cols, string[] operations, string[] values)
{
if (cols.Length != operations.Length || operations.Length != values.Length)
{
throw new Exception("col.Length != operation.Length != values.Length");
}
string query = "SELECT " + items[0];
for (int i = 1; i < items.Length; ++i)
{
query += ", " + items[i];
}
query += " FROM " + tableName + " WHERE " + cols[0] + operations[0] + "'" + values[0] + "' ";
for (int i = 1; i < cols.Length; ++i)
{
query += " AND " + cols[i] + operations[i] + "'" + values[i] + "' ";
}
Debug.LogFormat("query: {0}", query);
return ExecuteQuery(query);
}
public DataSet ExecuteQuery(string SQLString)
{
DataSet ds = new DataSet();
try
{
MySqlDataAdapter da = new MySqlDataAdapter(SQLString, conn);
da.Fill(ds);
}
catch (MySqlException ex)
{
throw new Exception(ex.Message);
}
return ds;
}
#endregion
#region 更新语句
public int UpdateInto(string tableName, string[] cols, string[] colsValues, string[] selectKeys, string[] selectValues)
{
string query = "UPDATE " + tableName + " SET " + cols[0] + " = " + "'" + colsValues[0] + "'";
for (int i = 1; i < colsValues.Length; ++i)
{
query += ", " + cols[i] + " =" + "'" + colsValues[i] + "'";
}
query += " WHERE " + selectKeys[0] + " = " + "'" + selectValues[0] + "' ";
for (int i = 1; i < selectKeys.Length; ++i)
{
query += " AND " + selectKeys[i] + " = " + "'" + selectValues[i] + "' ";
}
Debug.LogFormat("query: {0}", query);
return ExecuteNonQuery(query);
}
public int UpdateInto<T>(string tableName, string[] cols, T[] colsValues, string[] selectKeys, string[] selectValues) where T : struct
{
string query = "UPDATE " + tableName + " SET " + cols[0] + " = " + colsValues[0];
for (int i = 1; i < colsValues.Length; ++i)
{
query += ", " + cols[i] + " =" + colsValues[i];
}
query += " WHERE " + selectKeys[0] + " = " + "'" + selectValues[0] + "' ";
for (int i = 1; i < selectKeys.Length; ++i)
{
query += " AND " + selectKeys[i] + " = " + "'" + selectValues[i] + "' ";
}
Debug.LogFormat("query: {0}", query);
return ExecuteNonQuery(query);
}
public int UpdateInto(string tableName, string[] cols, object[] colsValues, string[] selectKeys, string[] selectValues)
{
string query = null;
if (colsValues[0] is string)
{
query = "UPDATE " + tableName + " SET " + cols[0] + " = " + string.Format("'{0}'", colsValues[0]);
}
else
{
query = "UPDATE " + tableName + " SET " + cols[0] + " = " + colsValues[0];
}
for (int i = 1; i < colsValues.Length; ++i)
{
if (colsValues[i] is string)
{
query += ", " + cols[i] + " =" + string.Format("'{0}'", colsValues[i]);
}
else
{
query += ", " + cols[i] + " =" + colsValues[i];
}
}
query += " WHERE " + selectKeys[0] + " = " + "'" + selectValues[0] + "' ";
for (int i = 1; i < selectKeys.Length; ++i)
{
query += " AND " + selectKeys[i] + " = " + "'" + selectValues[i] + "' ";
}
Debug.LogFormat("query: {0}", query);
return ExecuteNonQuery(query);
}
#endregion
#region 插入语句
public int InsertInto(string tableName, string[] cols, string[] values)
{
if (cols.Length != values.Length)
{
throw new Exception("columns.Length != colType.Length");
}
string query = "INSERT INTO " + tableName + " (" + cols[0];
for (int i = 1; i < cols.Length; ++i)
{
query += ", " + cols[i];
}
query += ") VALUES (" + "'" + values[0] + "'";
for (int i = 1; i < values.Length; ++i)
{
query += ", " + "'" + values[i] + "'";
}
query += ")";
Debug.LogFormat("query: {0}", query);
return ExecuteNonQuery(query);
}
#endregion
#region 删除语句
public int Delete(string tableName, string[] cols, string[] colsValues)
{
string query = "DELETE FROM " + tableName + " WHERE " + cols[0] + " = " + "'" + colsValues[0] + "'";
for (int i = 1; i < colsValues.Length; ++i)
{
query += " and " + cols[i] + " = " + "'" + colsValues[i] + "'";
}
Debug.LogFormat("query: {0}", query);
return ExecuteNonQuery(query);
}
#endregion
public int ExecuteNonQuery(string SQLString)
{
using (MySqlCommand cmd = new MySqlCommand(SQLString, conn))
{
try
{
int rows = cmd.ExecuteNonQuery();
return rows;
}
catch (MySqlException E)
{
throw new Exception(E.Message);
}
finally
{
cmd.Dispose();
}
}
}
}
本项目脚本 mysqlTools工具类
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Data;
public class MysqlTools
{
public static MysqlTools Instance { get; }
static MysqlTools()
{
Instance = new MysqlTools();
}
public Dictionary<int, Dictionary<string, object>> TableData(DataSet ds)
{
Dictionary<int, Dictionary<string,object>> tableList = new Dictionary<int, Dictionary<string, object>>();
int Count = -1;
for (int i = 0; i < ds.Tables.Count; i++)
{
for (int j = 0; j < ds.Tables[i].Rows.Count; j++)
{
Count++;
tableList.Add(Count, new Dictionary<string, object>());
var temp = ds.Tables[i];
var obj = temp.Rows[j].ItemArray;
for (int k = 0; k < obj.Length; k++)
{
string tableName = temp.Columns[k].ToString();
tableList[j].Add(tableName, obj[k]);
}
}
}
return tableList;
}
public object GetValue(DataSet ds,string Name)
{
for (int i = 0; i < ds.Tables.Count; i++)
{
for (int j = 0; j < ds.Tables[i].Rows.Count; j++)
{
var temp = ds.Tables[i];
var obj = temp.Rows[j].ItemArray;
for (int k = 0; k < obj.Length; k++)
{
string tableName = temp.Columns[k].ToString();
if(tableName == Name)
{
return obj[k];
}
}
}
}
return null;
}
public object[] GetValues(DataSet ds, string Name)
{
List<object> list = new List<object>();
for (int i = 0; i < ds.Tables.Count; i++)
{
for (int j = 0; j < ds.Tables[i].Rows.Count; j++)
{
var temp = ds.Tables[i];
var obj = temp.Rows[j].ItemArray;
for (int k = 0; k < obj.Length; k++)
{
string tableName = temp.Columns[k].ToString();
if (tableName == Name)
{
list.Add(obj[k]);
}
}
}
}
return list.Count == 0 ? null : list.ToArray();
}
}
本项目脚本Test
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Test : MonoBehaviour
{
void Start()
{
var mySqlTools = new SqlHelper("127.0.0.1", "3306", "root", "123456", "user");
mySqlTools.Open();
FindMysql(mySqlTools, "userdata", new[] { "UID", "User", "Password" });
mySqlTools.Close();
}
void FindMysql(SqlHelper mySqlTools,string tableName,string[] items)
{
var ds = mySqlTools.Select(tableName, items);
var pairs = MysqlTools.Instance.TableData(ds);
DebugMysql(pairs);
}
private void DebugMysql(Dictionary<int,Dictionary<string,object>> pairs)
{
foreach (var Line in pairs)
{
foreach (var table in Line.Value)
{
string tableList = string.Format("第{0}行,表字段名对应数据是 {1}", Line.Key + 1, table);
print(tableList);
}
}
}
}
使用数据库添/删/改/查
切记使用SqlHelper所有方法除了Connent方法外 其他方法一定要先Open(),使用完后在Close() 掉
插入数据库方法
var mySqlTools = new SqlHelper("127.0.0.1", "3306", "root", "123456", "user");
mySqlTools.Open();
mySqlTools.InsertInto("userdata", new[] { "UID", "User", "Password" },new[] {"水神","ddxj1","123456" });
mySqlTools.Close();
运行后如下图
更改数据方法
var mySqlTools = new SqlHelper("127.0.0.1", "3306", "root", "123456", "user");
mySqlTools.Open();
mySqlTools.UpdateInto("userdata",new[] {"Password" },new[] {"456789" },new[] { "User"},new[] { "ddxj1"});
mySqlTools.Close();
运行结果于下图
更改数据第二种方式
(Ints字段在数据库为int) (Strings 字段在数据库为text)
需求:查找数据库Ints字段为12369 更新对应表(Ints=555和Strings=账号) 注意:Ints是值类型 更改数据应该写555 不要写"555" 执行下面代码后
var mySqlTools = new SqlHelper("127.0.0.1", "3306", "root", "123456", "user");
mySqlTools.Open();
mySqlTools.UpdateInto("data1", new[] { "Ints", "Strings" }, new object[] { 555, "账号" }, new[] { "Ints" }, new[] { "12369" });
mySqlTools.Close();
删除数据方法
var mySqlTools = new SqlHelper("127.0.0.1", "3306", "root", "123456", "user");
mySqlTools.Open();
mySqlTools.Delete("userdata", new[] { "User" }, new[] { "ddxj1" });
mySqlTools.Close();
代码运行结果如下
数据库查询方法
需求:查询表中User 为imdork 对应UID 对应数据 代码如下:
var mySqlTools = new SqlHelper("127.0.0.1", "3306", "root", "123456", "user");
mySqlTools.Open();
var ds = mySqlTools.SelectWhere("userdata", new[] { "UID" }, new[] { "User" }, new[] { "=" }, new[] { "imdork" });
object values = MysqlTools.Instance.GetValue(ds, "UID");
print(values);
mySqlTools.Close();
最后控制台打印:
问题解决方案
如果Mysql安装时出现问题
注:如果跟着楼上步骤没有任何问题,下面就不用跟着做了。
如果在控制台输入以下指令出现问题
mysqld --install
如果显示The service already exists!
解决办法 先以管理员打开控制台 输入
sc query mysql
如上图 如果发现有则输入
sc delete mysql
然后在控制台输入指令
sc query mysql
则表示删除成功
|