Unity连接数据库MySQL
1.运行环境:Win7 64位,Unity3.5.0,MySQL5.5
2.在Unity新建一个场景,保存并命名为Unity_MySQL。
3.新建一个C#Script,命名为CMySql.cs。
4.下面是CMySql.cs脚本的内容:
using UnityEngine;
using System;
using System.Collections;
using System.Data;
using MySql.Data.MySqlClient;
public class CMySql : MonoBehaviour {
public static MySqlConnection dbConnection;//Just like MyConn.conn in StoryTools before
static string host = "127.0.0.1";
static string id = "root"; //***不要变***
static string pwd = "zym123"; //密码
static string database = "unity";//数据库名
static string result = "";
private string strCommand = "Select ID from unity ;";
public static DataSet MyObj;
void OnGUI()
{
host = GUILayout.TextField( host, 200, GUILayout.Width(200));
id = GUILayout.TextField( id, 200, GUILayout.Width(200));
pwd = GUILayout.TextField( pwd, 200, GUILayout.Width(200));
if(GUILayout.Button("Test"))
{
string connectionString = string.Format("Server = {0}; Database = {1}; User ID = {2}; Password = {3};",host,database,id,pwd);
openSqlConnection(connectionString);
MyObj = GetDataSet(strCommand);
//读取数据函数
ReaderData();
}
GUILayout.Label(result);
}
// On quit
public static void OnApplicationQuit()
{
closeSqlConnection();
}
// Connect to database
private static void openSqlConnection(string connectionString)
{
dbConnection = new MySqlConnection(connectionString);
dbConnection.Open();
result = dbConnection.ServerVersion; //获得MySql的版本
}
// Disconnect from database
private static void closeSqlConnection()
{
dbConnection.Close();
dbConnection = null;
}
// MySQL Query
public static void doQuery(string sqlQuery)
{
IDbCommand dbCommand = dbConnection.CreateCommand();
dbCommand.CommandText = sqlQuery;
IDataReader reader = dbCommand.ExecuteReader();
reader.Close();
reader = null;
dbCommand.Dispose();
dbCommand = null;
}
#region Get DataSet
public DataSet GetDataSet(string sqlString)
{
DataSet ds = new DataSet();
try
{
MySqlDataAdapter da = new MySqlDataAdapter(sqlString, dbConnection);
da.Fill(ds);
}
catch (Exception ee)
{
throw new Exception("SQL:" + sqlString + "\n" + ee.Message.ToString());
}
return ds;
}
#endregion
//读取数据函数
void ReaderData()
{
MySqlCommand mySqlCommand = new MySqlCommand("Select * from unity;", dbConnection);
MySqlDataReader reader = mySqlCommand.ExecuteReader();
try
{
while (reader.Read())
{
if (reader.HasRows)
{
print("ID:" + reader.GetInt32(0) + "--Name:" + reader.GetString(1) + "--Sex:" + reader.GetString(2));
}
}
}
catch (Exception)
{
Console.WriteLine("查询失败了!");
}
finally
{
reader.Close();
}
}
}
5.这个脚本中引用了System.Data.DLL,System.Drawing.DLL和MySql.Data.DLL。其中前两个可以在Unity3D的安装目录下找到:X:\Unity3D\Editor\Data\Mono\lib\mono\2.0\,最后一个MySql.Data.DLL可以从网上下载。将这3个DLL文件放到该项目的Assets文件夹下。并在VS2010中引用。
(Unity中的资源)
(vs2010中的资源)
6.启动MySQL。
7.创建一个数据库,命名为unity,并在其中新建一张表,也命名为unity。下图是表的设计视图。
8.在表中添加几条记录。(大家自己添加了~)
9.在Unity中将CMySql脚本拖放到Main Camera上去。运行Unity~运行界面如下:
10.点击Test按钮。运行结果如下:
11.并且我们在Game窗口可以看到我们使用的MySql的版本。
12.项目文件:在我个人资源中有下载。