1、导包
1)导入mysql.data.dll【mysql的】【必须和unity版本配合使用】、 2017.1.1unity需导入的.dll、提取码:o5sk 2)其余从你所使用unity中导出【Unity\Editor\Data\Mono\lib\mono\2.0】 3)如果能够正常连接数据库,但是打包报错,很有可能是需要修改下图[edit->projectseeting->playersetting]:
2、脚本
public static MySqlConnection con;//连接类对象
//host【ip地址,若是自己本机可设为localhost/127.0.0.1】
//database【连接数据库名】
//id 【mysql 账号名】
//pwd 【mysql密码名】
public static void OpenSql(){//连接
try{
string sqlString = string.Format("Server={0};Database={1};User ID ={2};Password ={3};", host, database, id, pwd);
con = new MySqlConnection(sqlString);
con.Open();
}
catch(Exception e){//这里catch中内容不能随便修改
...
}
}
public void Login(){//查询
OpenSql();
MySqlCommand mySqlCommand = new MySqlCommand("select *from table;", con);
MySqlDataReader reader = mySqlCommand.ExecuteReader();
try{
while (reader.Read()){
if (reader.HasRows && reader.GetString(1) == Username.text && reader.GetString(2) == Password.text){
//print("id:" + reader.GetInt32(0) + "--userName:" + reader.GetString(1) + "--password" + reader.GetString(2));
...
break;
}
}
}
catch(Exception e){
...
}
finally{
...
}
}
public void CloseConnection()//关闭连接,finally块中调用{
if(con != null){
con.Close();
con.Dispose();
con= null;
}
}