unity3D的數據庫連接操作

  1. using System;  
  2. using System.Collections;  
  3. using System.Data;  
  4. using MySql.Data.MySqlClient;  
  5. public class CMySql : MonoBehaviour {  
  6.     // Global variables   
  7.     public static MySqlConnection dbConnection;//Just like MyConn.conn in StoryTools before   
  8.      static string host = "192.168.1.100";  
  9.      static string id = "mysql";//這裏是你自己的數據庫的用戶名字,我一開始想用root,發現不行,後來添加了新的用戶纔可以   
  10.      static string pwd = "123456";  
  11.      static string database = "test";  
  12.      static string result = "";  
  13.       
  14. private string strCommand = "Select * from unity3d_test ORDER BY id;";  
  15. public static DataSet MyObj;  
  16.      void OnGUI()  
  17.      {  
  18.          host = GUILayout.TextField( host, 200, GUILayout.Width(200));  
  19.          id = GUILayout.TextField( id, 200, GUILayout.Width(200));  
  20.          pwd = GUILayout.TextField( pwd, 200, GUILayout.Width(200));  
  21.          if(GUILayout.Button("Test"))  
  22.          {  
  23.     string connectionString = string.Format("Server = {0}; Database = {1}; User ID = {2}; Password = {3};",host,database,id,pwd);  
  24.     openSqlConnection(connectionString);  
  25.       
  26.     MyObj = GetDataSet(strCommand);  
  27.          }   
  28.          GUILayout.Label(result);  
  29.      }    
  30.     // On quit   
  31.     public static void OnApplicationQuit() {  
  32.         closeSqlConnection();  
  33.     }  
  34.      
  35.     // Connect to database   
  36.     private static void openSqlConnection(string connectionString) {  
  37.         dbConnection = new MySqlConnection(connectionString);  
  38.         dbConnection.Open();  
  39.         result = dbConnection.ServerVersion;  
  40.         //Debug.Log("Connected to database."+result);   
  41.     }  
  42.      
  43.     // Disconnect from database   
  44.     private static void closeSqlConnection() {  
  45.         dbConnection.Close();  
  46.         dbConnection = null;  
  47.         //Debug.Log("Disconnected from database."+result);   
  48.     }  
  49.       
  50.     // MySQL Query   
  51.     public static void doQuery(string sqlQuery) {  
  52.         IDbCommand dbCommand = dbConnection.CreateCommand();      
  53.         dbCommand.CommandText = sqlQuery;  
  54.         IDataReader reader = dbCommand.ExecuteReader();  
  55.         reader.Close();  
  56.         reader = null;  
  57.         dbCommand.Dispose();  
  58.         dbCommand = null;  
  59.     }  
  60.     #region Get DataSet   
  61.     public  DataSet GetDataSet(string sqlString)  
  62.     {  
  63.         //string sql = UnicodeAndANSI.UnicodeAndANSI.UnicodeToUtf8(sqlString);   
  64.     
  65.     
  66.   DataSet ds = new DataSet();  
  67.         try  
  68.         {  
  69.             MySqlDataAdapter da = new MySqlDataAdapter(sqlString, dbConnection);  
  70.             da.Fill(ds);  
  71.      
  72.         }  
  73.         catch (Exception ee)  
  74.         {  
  75.      
  76.             throw new Exception("SQL:" + sqlString + "/n" + ee.Message.ToString());  
  77.         }  
  78.         return ds;  
  79.     
  80.     }  
  81.     #endregion    
  82. }  
[c-sharp] view plaincopy
  1. using UnityEngine;  
  2. using System;  
  3. using System.Collections;  
  4. using System.Data;  
  5. using MySql.Data.MySqlClient;  
  6. public class CMySql : MonoBehaviour {  
  7.     // Global variables  
  8.     public static MySqlConnection dbConnection;//Just like MyConn.conn in StoryTools before  
  9.      static string host = "192.168.1.100";  
  10.      static string id = "mysql";//這裏是你自己的數據庫的用戶名字,我一開始想用root,發現不行,後來添加了新的用戶纔可以  
  11.      static string pwd = "123456";  
  12.      static string database = "test";  
  13.      static string result = "";  
  14.       
  15. private string strCommand = "Select * from unity3d_test ORDER BY id;";  
  16. public static DataSet MyObj;  
  17.      void OnGUI()  
  18.      {  
  19.          host = GUILayout.TextField( host, 200, GUILayout.Width(200));  
  20.          id = GUILayout.TextField( id, 200, GUILayout.Width(200));  
  21.          pwd = GUILayout.TextField( pwd, 200, GUILayout.Width(200));  
  22.          if(GUILayout.Button("Test"))  
  23.          {  
  24.     string connectionString = string.Format("Server = {0}; Database = {1}; User ID = {2}; Password = {3};",host,database,id,pwd);  
  25.     openSqlConnection(connectionString);  
  26.       
  27.     MyObj = GetDataSet(strCommand);  
  28.          }   
  29.          GUILayout.Label(result);  
  30.      }    
  31.     // On quit  
  32.     public static void OnApplicationQuit() {  
  33.         closeSqlConnection();  
  34.     }  
  35.      
  36.     // Connect to database  
  37.     private static void openSqlConnection(string connectionString) {  
  38.         dbConnection = new MySqlConnection(connectionString);  
  39.         dbConnection.Open();  
  40.         result = dbConnection.ServerVersion;  
  41.         //Debug.Log("Connected to database."+result);  
  42.     }  
  43.      
  44.     // Disconnect from database  
  45.     private static void closeSqlConnection() {  
  46.         dbConnection.Close();  
  47.         dbConnection = null;  
  48.         //Debug.Log("Disconnected from database."+result);  
  49.     }  
  50.       
  51.     // MySQL Query  
  52.     public static void doQuery(string sqlQuery) {  
  53.         IDbCommand dbCommand = dbConnection.CreateCommand();      
  54.         dbCommand.CommandText = sqlQuery;  
  55.         IDataReader reader = dbCommand.ExecuteReader();  
  56.         reader.Close();  
  57.         reader = null;  
  58.         dbCommand.Dispose();  
  59.         dbCommand = null;  
  60.     }  
  61.     #region Get DataSet  
  62.     public  DataSet GetDataSet(string sqlString)  
  63.     {  
  64.         //string sql = UnicodeAndANSI.UnicodeAndANSI.UnicodeToUtf8(sqlString);  
  65.     
  66.     
  67.   DataSet ds = new DataSet();  
  68.         try  
  69.         {  
  70.             MySqlDataAdapter da = new MySqlDataAdapter(sqlString, dbConnection);  
  71.             da.Fill(ds);  
  72.      
  73.         }  
  74.         catch (Exception ee)  
  75.         {  
  76.      
  77.             throw new Exception("SQL:" + sqlString + "/n" + ee.Message.ToString());  
  78.         }  
  79.         return ds;  
  80.     
  81.     }  
  82.     #endregion   
  83. }  
 

C#代碼:

[c-sharp] view plaincopy
  1. using UnityEngine;  
  2. using System;  
  3. using System.Collections;  
  4. using System.Data;  
  5. public class DataBaseTest : MonoBehaviour {  
  6. public GUISkin myGUISkin = new GUISkin();  
  7. string strID = "";  
  8. string strName = "";  
  9. string strSex = "";  
  10. int Index = 1;  
  11. // Use this for initialization   
  12. void Start () {  
  13. }  
  14. void OnGUI()  
  15. {  
  16.   GUI.skin = myGUISkin;  
  17.   if (GUI.Button(new Rect(100,320,100,100),"Click Me"))  
  18.   {  
  19.    foreach(DataRow dr in CMySql.MyObj.Tables[0].Rows)  
  20.    {  
  21.     if (Index.ToString() == dr["ID"].ToString())  
  22.     {  
  23.      strID = dr["ID"].ToString();  
  24.      strName =  dr["Name"].ToString();  
  25.      strSex = dr["Sex"].ToString();  
  26.        
  27.      break;  
  28.     }  
  29.    }     
  30.    Index++;  
  31.     if(Index > 5)  
  32.    {  
  33.     Index = 1;   
  34.    }    
  35.      
  36.   }  
  37.   GUI.Label(new Rect(320,100,150,70),"DataBaseTest");  
  38.   GUI.Label(new Rect(300,210,150,70),strID);  
  39.   GUI.Label(new Rect(300,320,150,70),strName);  
  40.   GUI.Label(new Rect(300,430,150,70),strSex);  
  41.     
  42. }  
  43. }  
[c-sharp] view plaincopy
  1. using UnityEngine;  
  2. using System;  
  3. using System.Collections;  
  4. using System.Data;  
  5. public class DataBaseTest : MonoBehaviour {  
  6. public GUISkin myGUISkin = new GUISkin();  
  7. string strID = "";  
  8. string strName = "";  
  9. string strSex = "";  
  10. int Index = 1;  
  11. // Use this for initialization  
  12. void Start () {  
  13. }  
  14. void OnGUI()  
  15. {  
  16.   GUI.skin = myGUISkin;  
  17.   if (GUI.Button(new Rect(100,320,100,100),"Click Me"))  
  18.   {  
  19.    foreach(DataRow dr in CMySql.MyObj.Tables[0].Rows)  
  20.    {  
  21.     if (Index.ToString() == dr["ID"].ToString())  
  22.     {  
  23.      strID = dr["ID"].ToString();  
  24.      strName =  dr["Name"].ToString();  
  25.      strSex = dr["Sex"].ToString();  
  26.        
  27.      break;  
  28.     }  
  29.    }     
  30.    Index++;  
  31.     if(Index > 5)  
  32.    {  
  33.     Index = 1;   
  34.    }    
  35.      
  36.   }  
  37.   GUI.Label(new Rect(320,100,150,70),"DataBaseTest");  
  38.   GUI.Label(new Rect(300,210,150,70),strID);  
  39.   GUI.Label(new Rect(300,320,150,70),strName);  
  40.   GUI.Label(new Rect(300,430,150,70),strSex);  
  41.     
  42. }  
  43. }  
 

2.導入dll
  同先前的帖子 , 將MySql.data.dll Import至Assets底下 , 然後再到Unity/Editor/Data/Frameworks/Mono.framework 中
將System.Data.dll 也一起Import至Assets內 , 當然 , 如果想顯示中文的話 , 請參考中文視頻教學 , 建立一個GUISkin與字型

3.建立數據庫內容
  主要是因為代碼中的這段內容
     static string host = "192.168.1.100";
     static string id = "mysql";
     static string pwd = "123456";
     static string database = "test";
     private string strCommand = "Select * from unity3d_test ORDER BY id;";
其中host ,id , pwd 請自行設定 , 簡單的說就是連進你的MySQL啦~
然後建立一個名為test的Database , 在這個test下建立一張table , 取名為 unity3d_test ,
接下來就為這張unity3d_test建立3個欄位 : ID , Name , Sex (記得將ID設定為primary key 且默認值為1)
再來自行填入5筆資料(5筆資料的原因是腳本那邊是設定成5筆資料一個循環 , 使用者可以自行更改腳本試試)

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

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

6.總結 
  以上部份是有關連線至數據庫後 , 再將資料用DataSet的方式獲得出來再加以顯示至介面上 , 歡迎各位高手能夠多多批評指教

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章