首先去官网下载一个MySQL
网址:https://dev.mysql.com/downloads/mysql/
我用的版本是5.5.62
然后下载了一个可视化工具
网址:https://www.navicat.com.cn/products#navicat
(15天免费用,过期的话就搞一个破解工具吧!)
然后去MySQL官网下载mysql.data.dll文件
我用的是Unity2018.3.0f2
附上一个mysql.data.dll链接
链接:https://pan.baidu.com/s/1p5uOUMgJ6caYMLI8b_YR6g
提取码:215w
然后放在Unity的Plugins文件夹中
然后创建代码:引用命名空间
开始测试连接:
static string server;
static string database;
static string uID;
static string password;
static MySqlConnection mycon;
void Start()
{
//连接的本地电脑的所以直接用localhost了
server="localhost";
//数据库名称
database="mydatabase";
//帐号
uID="root";
//密码
password="root";
string constr="Server="+server+";Database="+database+";User Id="+uID+";Password="+password;
//建立连接的语句
//如果事本地数据库server为localhost,不是则输入server的地址
mycon = new MySqlConnection(constr);//建立连接
mycon.Open()
//Insert();
//Select()
mycon.Close(); //关闭连接
}
来给数据库插入一条记录,写了一个方法,然后去上面Start里面调用
前提数据库要有这个表和这几个名,跟下面的insert插入命令里面的名称对应
static void Insert()
{
//插入指令
try
{
MySqlCommand mycmd = new MySqlCommand(
"insert into hiscores(id,name,score) values(1,'aaa',100)", mycon);
if (mycmd.ExecuteNonQuery()>0)
{
Debug.Log("Insert success!");
}
}
catch (Exception e)
{
throw new Exception("插入错误:"+e.Message.ToString());
}
}
然后调用方法运行一下程序
Unity没有报错,然后刷新一下表
成功插入
查询数据库
static void Select()
{
//查询指令
string selstr = "select * from hiscores";
MySqlCommand myselect = new MySqlCommand(selstr, mycon);
DataSet ds = new DataSet();
try
{
MySqlDataAdapter da = new MySqlDataAdapter(selstr, mycon);
da.Fill(ds);
Debug.Log("Query success!");
//读取第一个表中的所有的数据
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
for (int j = 0; j < ds.Tables[0].Rows[i].ItemArray.Length; j++)
{
print("第一个表中的数据" +ds.Tables[0].Rows[i][j]);
}
}
/*
print("第一条记录的长度"+ ds.Tables[0].Rows[0].ItemArray.Length);
print(ds.Tables[0].Rows[0].ItemArray[1].ToString());
print("数据库表里面有多少条记录:"+ ds.Tables[0].Rows.Count);
print("数据库中有多少个表:"+ ds.Tables.Count);
*/
}
catch (Exception e)
{
throw new Exception("查询错误:" + e.Message.ToString());
}
}
调用这个方法。成功查询到这个表的所有记录
End…