Skip to main content

数据库的连接和读取

Unity的脚本是基于开源的.net框架'Mono', 因此它带给我们很大的扩展空间!!

到这里根据需要下载对应的Dll文件。 以MySql为例,我们可以进入http://mono-project.com/MySQL根据说明下载对应文件,将"mysql.data.dll"拷到脚本对应的目录下。 参考网页中的示例代码我们得改改才能正确在Unity中运行:(2009-11.19更新:其实不用改也行,当初没添加 System.Data.dll

必须从这目录拷:..\Unity\Editor\Data \MonoCompiler.frameworkAssets目录下)

去掉"using System.Data" 否则报错

"The type or namespace name Data' does not exist in the namespace System'. Are you missing an assembly

数据库test 表 unity3d_test 字段 ID Name Sex

//———————————————————————————————————————————-
//———————————————————————————————————————————-
using UnityEngine;
using System;
using System.Collections;
using System.Data;
using MySql.Data.MySqlClient;
public class CMySql : MonoBehaviour {
// Global variables
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 = ""; //数据库密码
static string database = "test"; //数据库名
static string result = "";

private string strCommand = "Select * from unity3d_test ORDER BY id;"; //查询unity3d_test表
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);
}
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;
print(connectionString);
//Debug.Log("Connected to database."+result);
print(dbConnection.CreateCommand());
}

// Disconnect from database
private static void closeSqlConnection() {
dbConnection.Close();
dbConnection = null;
//Debug.Log("Disconnected from database."+result);
}

// 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)
{
//string sql = UnicodeAndANSI.UnicodeAndANSI.UnicodeToUtf8(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
}

第二个脚本

using UnityEngine;
using System;
using System.Collections;
using System.Data;

public class DataBaseTest : MonoBehaviour {
public GUISkin myGUISkin = new GUISkin();
string strID = "";
string strName = "";
string strSex = "";
int Index = 1;
// Use this for initialization
void Start () {
}

void OnGUI()
{
GUI.skin = myGUISkin;
if (GUI.Button(new Rect(100,320,100,100),"Click Me"))
{
foreach(DataRow dr in CMySql.MyObj.Tables[0].Rows)
{
if (Index.ToString() == dr["ID"].ToString())
{
strID = dr["ID"].ToString();
strName = dr["Name"].ToString();
strSex = dr["Sex"].ToString();

break;
}
}
Index++;
if(Index > 5)
{
Index = 1;
}
}
GUI.Label(new Rect(320,100,150,70),"DataBaseTest");
GUI.Label(new Rect(300,210,150,70),strID);
GUI.Label(new Rect(300,320,150,70),strName);
GUI.Label(new Rect(300,430,150,70),strSex);
}
}

此时在Unity中是可以正确运行了,不过打包后运行会出错,根据出错信息我网上查下好像是国际化问题.到..\Unity\Editor \Data\Frameworks\Mono.framework目录下将I18N.CJK.dll、 I18N.dll 、I18N.West.dll拷到脚本目录下就行了。

本条目发布于2010年4月26日。属于Unity脚本分类。