Unity引擎链接mySQL数据库

需要unity3d3.5pro版本,所以先确认自己用的是不是下载地址:http://game.ceeger.com/forum/read.php?tid=870(经测试好用)

安装mysql-connector-net我装的是6.0.3下载地址:

安装mono,官网地址http://www.go-mono.com/mono-downloads/download.html我下的是2.10.8

复制文件

Mono-2.10.8\lib\mono\gac\System.Drawing\4.0.0.0__b03f5f7f11d50a3a\System.Drawing.dll

Mono-2.10.8\lib\mono\gac\System.Data\2.0.0.0__b77a5c561934e089\System.Data.dll

C:\ProgramFiles(x86)\MySQL\MySQLConnectorNet6.0.3\Assemblies\MySql.Data.dll

复制到Assets目录里(就是项目工程目录,找不到拖出去TJJTDS)

没mysql的,下载XAMPP进行安装,我的版本是1.7.4度娘搜索XAMPP很多,就不给地址了。安装时记得把mysql选上。

确保mysql可以运行,打开浏览器,输入地址:http://127.0.0.1/phpmyadmin/

修改root密码123

添加库文件test

添加表unity3d

字段User_IDAUTO_INCREMENT

User_Namechar(10)

User_Sexchar(10)

随便添几条数据。

也可以使用管理工具,推荐HeidiSQL

之后可以使用下面这个PHP脚本测试下是否能连接成功。

使用方法,进入目录D:\xampp\htdocs\xampp建立PHP文件,1.php

<?php
$con = mysql_connect("127.0.0.1","root","123");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }
?>

然后通过http://127.0.0.1/xampp/1.php如果什么都不显示,就对了。

配置结束,下面是代码:

建立C#脚本:CMySql.cs代码如下

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 = "123";  
     static string database = "test";  
     static string result = "";  
      
private string strCommand = "Select * from unity3d ORDER BY id;";  
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;  
        //Debug.Log("Connected to database."+result);  
    }  
      
    // 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  
}

建立C#脚本:DataBaseTest.cs代码如下

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["User_ID"].ToString();  
     strName =  dr["User_Name"].ToString();  
     strSex = dr["User_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);  
}  
}

建立GameObject

建立完GameObject後將上面兩個腳本掛上去,如果有建立GUISkin,記得指定GUISkin

執行

執行後先按Test按鈕來連接數據庫,然後再按"ClickMe"來顯示數據庫內的內容

相关推荐