1. 程式人生 > >Unity3D連線本地或區域網MySQL資料庫

Unity3D連線本地或區域網MySQL資料庫

準備工作:

1、開啟 Unity3D 安裝目錄,到這個路徑下 Editor > Data > Mono > lib > mono > 2.0 拷貝出下圖的五個動態連結庫,放到 Unity3D 工程目錄下 Assets/Plugins 資料夾中。這裡我想重點說一下,在使用過程中這五個動態連結庫需要與 Unity3D 版本匹配,也就是說你不要在 Uniyt3D 5.3 版本拷貝出來,拿去 Uniyt3D 5.4 版本中使用,這是有可能出問題的,最好是在自己的 Unity3D 安裝目錄下去拷貝。I18N.CJK.dll 這個連結庫,如果是 PC 端連線資料庫可以不需要,如果是移動端連線資料庫就必須要。

2、網上下載一個 MySql.Data.dll 動態連結庫,也放到 Unity3D 工程目錄下 Assets/Plugins 資料夾中。

using MySql.Data.MySqlClient;
  2 using System;
  3 using System.Data;
  4 
  5 public class MySqlAccess
  6 {
  7     public static MySqlConnection mySqlConnection;//連線類物件
  8 
  9     private static string host;     //IP地址。如果只是在本地的話,寫localhost就可以。
 10     private static string id;       //使用者名稱。
 11     private static string pwd;      //密碼。
 12     private static string dataBase; //資料庫名稱。
 13 
 14     /// <summary>
 15     /// 構造方法
 16     /// </summary>
 17     /// <param name="_host">IP地址</param>
 18     /// <param name="_id">使用者名稱</param>
 19     /// <param name="_pwd">密碼</param>
 20     /// <param name="_dataBase">資料庫名稱</param>
 21     public MySqlAccess(string _host, string _id, string _pwd, string _dataBase)
 22     {
 23         host = _host;
 24         id = _id;
 25         pwd = _pwd;
 26         dataBase = _dataBase;
 27         OpenSql();
 28     }
 29 
 30     /// <summary>  
 31     /// 開啟資料庫  
 32     /// </summary>  
 33     public static void OpenSql()
 34     {
 35         try
 36         {
 37             //string.Format是將指定的 String型別的資料中的每個格式項替換為相應物件的值的文字等效項。  
 38             string mySqlString = string.Format("Database={0};Data Source={1};User Id={2};Password={3};", dataBase, host, id, pwd, "3306");
 39             mySqlConnection = new MySqlConnection(mySqlString);
 40             mySqlConnection.Open();
 41         }
 42         catch (Exception e)
 43         {
 44             throw new Exception("伺服器連線失敗,請重新檢查是否開啟MySql服務。" + e.Message.ToString());
 45         }
 46     }
 47 
 48     /// <summary>  
 49     /// 建立表  
 50     /// </summary>  
 51     /// <param name="name">表名</param>  
 52     /// <param name="colName">屬性列</param>  
 53     /// <param name="colType">屬性型別</param>  
 54     /// <returns></returns>  
 55     public DataSet CreateTable(string name, string[] colName, string[] colType)
 56     {
 57         if (colName.Length != colType.Length)
 58         {
 59             throw new Exception("輸入不正確:" + "columns.Length != colType.Length");
 60         }
 61         string query = "CREATE TABLE  " + name + "(" + colName[0] + " " + colType[0];
 62         for (int i = 1; i < colName.Length; i++)
 63         {
 64             query += "," + colName[i] + " " + colType[i];
 65         }
 66         query += ")";
 67         return QuerySet(query);
 68     }
 69 
 70     /// <summary>  
 71     /// 建立具有id自增的表  
 72     /// </summary>  
 73     /// <param name="name">表名</param>  
 74     /// <param name="col">屬性列</param>  
 75     /// <param name="colType">屬性列型別</param>  
 76     /// <returns></returns>  
 77     public DataSet CreateTableAutoID(string name, string[] col, string[] colType)
 78     {
 79         if (col.Length != colType.Length)
 80         {
 81             throw new Exception("columns.Length != colType.Length");
 82         }
 83         string query = "CREATE TABLE  " + name + " (" + col[0] + " " + colType[0] + " NOT NULL AUTO_INCREMENT";
 84         for (int i = 1; i < col.Length; ++i)
 85         {
 86             query += ", " + col[i] + " " + colType[i];
 87         }
 88         query += ", PRIMARY KEY (" + col[0] + ")" + ")";
 89         return QuerySet(query);
 90     }
 91 
 92     /// <summary>  
 93     /// 插入一條資料,包括所有,不適用自動累加ID。  
 94     /// </summary>  
 95     /// <param name="tableName">表名</param>  
 96     /// <param name="values">插入值</param>  
 97     /// <returns></returns>  
 98     public DataSet InsertInto(string tableName, string[] values)
 99     {
100         string query = "INSERT INTO " + tableName + " VALUES (" + "'" + values[0] + "'";
101         for (int i = 1; i < values.Length; ++i)
102         {
103             query += ", " + "'" + values[i] + "'";
104         }
105         query += ")";
106         return QuerySet(query);
107     }
108 
109     /// <summary>  
110     /// 插入部分ID  
111     /// </summary>  
112     /// <param name="tableName">表名</param>  
113     /// <param name="col">屬性列</param>  
114     /// <param name="values">屬性值</param>  
115     /// <returns></returns>  
116     public DataSet InsertInto(string tableName, string[] col, string[] values)
117     {
118         if (col.Length != values.Length)
119         {
120             throw new Exception("columns.Length != colType.Length");
121         }
122         string query = "INSERT INTO " + tableName + " (" + col[0];
123         for (int i = 1; i < col.Length; ++i)
124         {
125             query += ", " + col[i];
126         }
127         query += ") VALUES (" + "'" + values[0] + "'";
128         for (int i = 1; i < values.Length; ++i)
129         {
130             query += ", " + "'" + values[i] + "'";
131         }
132         query += ")";
133         return QuerySet(query);
134     }
135 
136     /// <summary>  
137     /// 查詢表資料 
138     /// </summary>  
139     /// <param name="tableName">表名</param>  
140     /// <param name="items">需要查詢的列</param>  
141     /// <param name="whereColName">查詢的條件列</param>  
142     /// <param name="operation">條件操作符</param>  
143     /// <param name="value">條件的值</param>  
144     /// <returns></returns>  
145     public DataSet Select(string tableName, string[] items, string[] whereColName, string[] operation, string[] value)
146     {
147         if (whereColName.Length != operation.Length || operation.Length != value.Length)
148         {
149             throw new Exception("輸入不正確:" + "col.Length != operation.Length != values.Length");
150         }
151         string query = "SELECT " + items[0];
152         for (int i = 1; i < items.Length; i++)
153         {
154             query += "," + items[i];
155         }
156         query += "  FROM  " + tableName + "  WHERE " + " " + whereColName[0] + operation[0] + " '" + value[0] + "'";
157         for (int i = 1; i < whereColName.Length; i++)
158         {
159             query += " AND " + whereColName[i] + operation[i] + "' " + value[i] + "'";
160         }
161         return QuerySet(query);
162     }
163 
164     /// <summary>  
165     /// 更新表資料 
166     /// </summary>  
167     /// <param name="tableName">表名</param>  
168     /// <param name="cols">更新列</param>  
169     /// <param name="colsvalues">更新的值</param>  
170     /// <param name="selectkey">條件:列</param>  
171     /// <param name="selectvalue">條件:值</param>  
172     /// <returns></returns>  
173     public DataSet UpdateInto(string tableName, string[] cols, string[] colsvalues, string selectkey, string selectvalue)
174     {
175         string query = "UPDATE " + tableName + " SET " + cols[0] + " = " + colsvalues[0];
176         for (int i = 1; i < colsvalues.Length; ++i)
177         {
178             query += ", " + cols[i] + " =" + colsvalues[i];
179         }
180         query += " WHERE " + selectkey + " = " + selectvalue + " ";
181         return QuerySet(query);
182     }
183 
184     /// <summary>  
185     /// 刪除表資料  
186     /// </summary>  
187     /// <param name="tableName">表名</param>  
188     /// <param name="cols">條件:刪除列</param>  
189     /// <param name="colsvalues">刪除該列屬性值所在得行</param>  
190     /// <returns></returns>  
191     public DataSet Delete(string tableName, string[] cols, string[] colsvalues)
192     {
193         string query = "DELETE FROM " + tableName + " WHERE " + cols[0] + " = " + colsvalues[0];
194         for (int i = 1; i < colsvalues.Length; ++i)
195         {
196             query += " or " + cols[i] + " = " + colsvalues[i];
197         }
198         return QuerySet(query);
199     }
200 
201     /// <summary>
202     /// 釋放
203     /// </summary>
204     public void Close()
205     {
206         if (mySqlConnection != null)
207         {
208             mySqlConnection.Close();
209             mySqlConnection.Dispose();
210             mySqlConnection = null;
211         }
212     }
213 
214     /// <summary>    
215     /// 執行Sql語句  
216     /// </summary>  
217     /// <param name="sqlString">sql語句</param>  
218     /// <returns></returns>  
219     public static DataSet QuerySet(string sqlString)
220     {
221         if (mySqlConnection.State == ConnectionState.Open)
222         {
223             DataSet ds = new DataSet();
224             try
225             {
226                 MySqlDataAdapter mySqlDataAdapter = new MySqlDataAdapter(sqlString, mySqlConnection);
227                 mySqlDataAdapter.Fill(ds);
228             }
229             catch (Exception e)
230             {
231                 throw new Exception("SQL:" + sqlString + "/n" + e.Message.ToString());
232             }
233             finally
234             {
235             }
236             return ds;
237         }
238         return null;
239     }
240 }
接下來我們就可以訪問資料庫了
 1 using UnityEngine;
 2 using System.Data;
 3 
 4 public class Test : MonoBehaviour
 5 {
 6     private void Start()
 7     {
 8         MySqlAccess mySql = new MySqlAccess("localhost", "root", "root", "Test");
 9         mySql.CreateTableAutoID("tableTest", new string[] { "id", "name", "age" }, new string[] { "int", "text", "text" });
10         mySql.InsertInto("tableTest", new string[] { "name", "age" }, new string[] { "張三", "28" });
11         mySql.InsertInto("tableTest", new string[] { "name", "age" }, new string[] { "李四", "20" });
12         for (int i = 1; i < 3; i++)
13         {
14             DataSet ds = mySql.Select("tableTest", new string[] { "name", "age" }, new string[] { "id" }, new string[] { "=" }, new string[] { i.ToString() });
15             if (ds != null)
16             {
17                 DataTable table = ds.Tables[0];
18                 foreach (DataRow row in table.Rows)
19                 {
20                     foreach (DataColumn column in table.Columns)
21                     {
22                         Debug.Log(row[column]);
23                     }
24                 }
25             } 
26         }
27         mySql.Close();
28     }
29 }

轉載:https://www.cnblogs.com/xiaoyulong/p/8686886.html#4053314