Unity連線MySQL資料庫
阿新 • • 發佈:2019-01-05
前兩天研究Socket和C#連線資料庫其實都是為了將這些和unity結合使用做的基礎學習。
所以最後都會歸結到Unity上面。其實學會了C#關於資料庫的操作,Unity肯定也就會了。
首先準備工作,新建一個unity專案就不用講了。在unity專案工程下建立一個Plugins資料夾,裡面存放的都是一些需要用到的動態連結庫檔案。主要有五個檔案。
如圖:
然後在C#封裝了一個SQLAccess類。這個類主要做的就是和資料庫連線和組拼了增刪改查的SQL語句。
若需要在區域網下訪問資料庫,則講host改為本機的IP地址。using System; using System.Collections.Generic; using System.Data; using System.Linq; using System.Text; using MySql.Data.MySqlClient; namespace Assets { public class SqlAccess { public static MySqlConnection mySqlConnection;//連線類物件 private static string database = "test"; private static string host = "127.0.0.1"; private static string id = "root"; private static string pwd = "123"; public SqlAccess() { OpenSql(); } /// <summary> /// 開啟資料庫 /// </summary> public static void OpenSql() { try { //string.Format是將指定的 String型別的資料中的每個格式項替換為相應物件的值的文字等效項。 string sqlString = string.Format("Database={0};Data Source={1};User Id={2};Password={3};", database, host, id, pwd, "3306"); mySqlConnection = new MySqlConnection(sqlString); mySqlConnection.Open(); } catch (Exception) { throw new Exception("伺服器連線失敗....."); } } /// <summary> /// 建立表 /// </summary> /// <param name="name">表名</param> /// <param name="colName">屬性列</param> /// <param name="colType">屬性型別</param> /// <returns></returns> public DataSet CreateTable(string name, string[] colName, string[] colType) { if (colName.Length != colType.Length) { throw new Exception("輸入不正確:" + "columns.Length != colType.Length"); } string query = "CREATE TABLE " + name + "(" + colName[0] + " " + colType[0]; for (int i = 1; i < colName.Length; i++) { query += "," + colName[i] + " " + colType[i]; } query += ")"; return QuerySet(query); } /// <summary> /// 建立具有id自增的表 /// </summary> /// <param name="name">表名</param> /// <param name="col">屬性列</param> /// <param name="colType">屬性列型別</param> /// <returns></returns> public DataSet CreateTableAutoID(string name, string[] col, string[] colType) { if (col.Length != colType.Length) { throw new Exception("columns.Length != colType.Length"); } string query = "CREATE TABLE " + name + " (" + col[0] + " " + colType[0] + " NOT NULL AUTO_INCREMENT"; for (int i = 1; i < col.Length; ++i) { query += ", " + col[i] + " " + colType[i]; } query += ", PRIMARY KEY (" + col[0] + ")" + ")"; // Debug.Log(query); return QuerySet(query); } /// <summary> /// 查詢 /// </summary> /// <param name="tableName">表名</param> /// <param name="items">需要查詢的列</param> /// <param name="whereColName">查詢的條件列</param> /// <param name="operation">條件操作符</param> /// <param name="value">條件的值</param> /// <returns></returns> public DataSet Select(string tableName, string[] items, string[] whereColName, string[] operation, string[] value) { if (whereColName.Length != operation.Length || operation.Length != value.Length) { throw new Exception("輸入不正確:" + "col.Length != operation.Length != values.Length"); } string query = "SELECT " + items[0]; for (int i = 1; i < items.Length; i++) { query += "," + items[i]; } query += " FROM " + tableName + " WHERE " + " " + whereColName[0] + operation[0] + " '" + value[0] + "'"; for (int i = 1; i < whereColName.Length; i++) { query += " AND " + whereColName[i] + operation[i] + "' " + value[i] + "'"; } return QuerySet(query); } /// <summary> /// 刪除 /// </summary> /// <param name="tableName">表名</param> /// <param name="cols">條件:刪除列</param> /// <param name="colsvalues">刪除該列屬性值所在得行</param> /// <returns></returns> public DataSet Delete(string tableName, string[] cols, string[] colsvalues) { string query = "DELETE FROM " + tableName + " WHERE " + cols[0] + " = " + colsvalues[0]; for (int i = 1; i < colsvalues.Length; ++i) { query += " or " + cols[i] + " = " + colsvalues[i]; } // Debug.Log(query); return QuerySet(query); } /// <summary> /// 更新 /// </summary> /// <param name="tableName">表名</param> /// <param name="cols">更新列</param> /// <param name="colsvalues">更新的值</param> /// <param name="selectkey">條件:列</param> /// <param name="selectvalue">條件:值</param> /// <returns></returns> public DataSet UpdateInto(string tableName, string[] cols, string[] colsvalues, string selectkey, string selectvalue) { string query = "UPDATE " + tableName + " SET " + cols[0] + " = " + colsvalues[0]; for (int i = 1; i < colsvalues.Length; ++i) { query += ", " + cols[i] + " =" + colsvalues[i]; } query += " WHERE " + selectkey + " = " + selectvalue + " "; return QuerySet(query); } /// <summary> /// 插入一條資料,包括所有,不適用自動累加ID。 /// </summary> /// <param name="tableName">表名</param> /// <param name="values">插入值</param> /// <returns></returns> public DataSet InsertInto(string tableName, string[] values) { string query = "INSERT INTO " + tableName + " VALUES (" + "'" + values[0] + "'"; for (int i = 1; i < values.Length; ++i) { query += ", " + "'" + values[i] + "'"; } query += ")"; // Debug.Log(query); return QuerySet(query); } /// <summary> /// 插入部分 /// </summary> /// <param name="tableName">表名</param> /// <param name="col">屬性列</param> /// <param name="values">屬性值</param> /// <returns></returns> public DataSet InsertInto(string tableName, string[] col, string[] values) { if (col.Length != values.Length) { throw new Exception("columns.Length != colType.Length"); } string query = "INSERT INTO " + tableName + " (" + col[0]; for (int i = 1; i < col.Length; ++i) { query += ", " + col[i]; } query += ") VALUES (" + "'" + values[0] + "'"; for (int i = 1; i < values.Length; ++i) { query += ", " + "'" + values[i] + "'"; } query += ")"; // Debug.Log(query); return QuerySet(query); } /// <summary> /// /// 執行Sql語句 /// </summary> /// <param name="sqlString">sql語句</param> /// <returns></returns> public static DataSet QuerySet(string sqlString) { if (mySqlConnection.State == ConnectionState.Open) { DataSet ds = new DataSet(); try { MySqlDataAdapter mySqlDataAdapter = new MySqlDataAdapter(sqlString,mySqlConnection); mySqlDataAdapter.Fill(ds); } catch (Exception e) { throw new Exception("SQL:" + sqlString + "/n" + e.Message.ToString()); } finally { } return ds; } return null; } public void Close() { if (mySqlConnection != null) { mySqlConnection.Close(); mySqlConnection.Dispose(); mySqlConnection = null; } } } }
然後在Unity新建一個指令碼,放在場景中任何物體都可以,用來操作資料庫
using Assets; using UnityEngine; using System.Collections; using System.Data; using UnityEngine.UI; public class Test : MonoBehaviour { public Text text; void Start () { SqlAccess sql = new SqlAccess(); // sql.CreateTableAutoID("jl", new string[] { "id", "name", "qq", "email", "blog" }, new string[] { "int", "text", "text", "text", "text" }); //sql.InsertInto("jl", new string[] { "name", "qq", "email", "blog" }, new string[] { "jianglei", "289187120", "
[email protected]", "jianglei.com" }); // sql.InsertInto("jl", new string[] { "name", "qq", "email", "blog" }, new string[] { "lizhih", "34546546", "[email protected]", "lizhih.com" }); // sql.Delete("jl", new string[] {"id"}, new string[] {"2"}); DataSet ds=sql.Select("jl", new string[] { "name", "qq" }, new string[] { "id" }, new string[] { "=" }, new string[] { "1" }); if (ds!=null) { DataTable table = ds.Tables[0]; foreach (DataRow dataRow in table.Rows) { foreach (DataColumn dataColumn in table.Columns) { Debug.Log(dataRow[dataColumn]); text.text += " "+dataRow[dataColumn].ToString(); } } } sql.Close(); } void Update () { } }
最後點選執行,觀察控制檯輸出和Navicat的資料庫就可以看到執行結果了。