using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using UnityEngine;
public class MysqlDataCompile : MonoBehaviour {
public int id;
public string modelname;
public double width;
public double heigh;
void Start()
{
try
{
//数据库的增删改查
string MySqlStr = "Database=;server=;User Id=;Password=;";
MySqlConnection mySqlcon = new MySqlConnection(MySqlStr);//连接数据库;
mySqlcon.Open();
//查
string str = "select * from furnituretest where id=" + id + ";";
MySqlCommand mySqlCom = new MySqlCommand(str, mySqlcon);
CheckedMySql(mySqlCom);
//增
//str = "insert into furnituretest values(" + id + ",'" + modelname + "'," + width + ",'" + heigh + "');";
//mySqlCom = new MySqlCommand(str, mySqlcon);
//IducMySql(mySqlCom);
//删
//str = "delete from furnituretest where id=5;";
//mySqlCom = new MySqlCommand(str, mySqlcon);
//IducMySql(mySqlCom);
// 改
//str = "update furnituretest set width=" + width + " where id=" + id + ";";
//mySqlCom = new MySqlCommand(str, mySqlcon);
//IducMySql(mySqlCom);
//GetId(7);
}
catch (Exception e)
{
throw new Exception("服务器连接失败,请重新检查是否打开MySql服务。" + e.Message.ToString());
}
}
//(查)
static private void CheckedMySql(MySqlCommand mySqlcom)
{
MySqlDataReader read = mySqlcom.ExecuteReader();
try
{
if (read.Read())
{
if (read.HasRows)//查找
{
Debug.Log("id:" + read.GetInt32("id"));
Debug.Log("modelname:" + read.GetString("modelname"));
Debug.Log("width:" + read.GetDouble("width"));
Debug.Log("height:" + read.GetDouble("height"));
}
}
}
catch (Exception e)
{
throw e;
}
finally
{
read.Close();
}
}
//增 删 改 查
static private void IducMySql(MySqlCommand mySqlcom)
{
try
{
mySqlcom.ExecuteNonQuery();
}
catch (Exception e)
{
Debug.Log("已存在");
//throw e;
}
}
//指定ID参数打印相关信息
static private void GetId(int id)
{
string MySqlStr = "Database=;server=;User Id=;Password=;";
MySqlConnection mySqlcon = new MySqlConnection(MySqlStr);
mySqlcon.Open();
string str = "select * from furnituretest where id=" + id;//注意 别把分号打上去;
MySqlCommand mySqlCom = new MySqlCommand(str, mySqlcon);
MySqlDataReader reader = mySqlCom.ExecuteReader();
try
{
while (reader.Read())
{
if (reader.HasRows)//查找
{
Debug.Log("id:" + reader.GetInt32("id"));
Debug.Log("modelname:" + reader.GetString("modelname"));
Debug.Log("width:" + reader.GetDouble("width"));
Debug.Log("height:" + reader.GetDouble("height"));
}
}
}
catch (Exception e)
{
throw e;
}
finally
{
reader.Close();
}
}
}
unity中需要导入五个dll:
Unity\Editor\Data\Mono\lib\mono\unity
目录下的
I18N.dll I18N.West.dll I18N.CJK.dll
Unity\Editor\Data\Mono\lib\mono\2.0
目录下的
System.Data.dll System.Drawing.dll
还需要 mysql5.0版本以上的
MySql.Data.dll