Unity和MySQL資料庫連線 (一 NGUI形式 )
1. 把下面這個程式碼放在專案檔案裡,無須拖拽到任何物體上。
2. 把下面NewBehaviourScript.cs放到主相機上。按照pulic名字拖拽相應物體如圖:using UnityEngine; using System; using System.Data; using System.Collections; using MySql.Data.MySqlClient; using MySql.Data; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; public class SqlAccess { public static MySqlConnection dbConnection;//資料庫 // public static MySqlConnection systemDbConnection;// 系統資料庫 // //如果只是在本地的話,寫localhost就可以。// // static string host = "localhost"; // //如果是區域網,那麼寫上本機的區域網IP// static string host = "127.0.0.1"; static string id = "root"; static string pwd = ""; // 不需要密碼 // static string database = "db"; // 資料庫名字// public SqlAccess()// 訪問資料庫 // { OpenSql();//開啟資料庫// OpenSystem();//開啟系統// } public static void OpenSystem()//開啟系統 // { try { // 連線字串 = 格式化 (伺服器IP,資料 概要,ID,密碼,介面)// string connectionString = string.Format("Server = {0};port={4};Database = {1}; User ID = {2}; Password = {3};",host,"information_schema",id,pwd,"3306"); // 系統連線 = new 一個MYSQL的連線(連線字串) // systemDbConnection = new MySqlConnection(connectionString); // 系統連線成功 // systemDbConnection.Open(); }catch (Exception e)//丟擲異常資訊 // { throw new Exception("伺服器連線失敗,請重新檢查是否開啟MySql服務。" + e.Message.ToString()); } } public static void OpenSql()// 開啟資料庫 // { try { // 連線字串 = 格式化 (伺服器IP,資料庫,ID,密碼,介面)// string connectionString = string.Format("Server = {0};port={4};Database = {1}; User ID = {2}; Password = {3};",host,database,id,pwd,"3306"); // 資料庫連線 = new 一個MYSQL的連線(連線字串) // dbConnection = new MySqlConnection(connectionString); // 資料庫連線成功 // dbConnection.Open(); }catch (Exception e)//丟擲異常資訊 // { throw new Exception("伺服器連線失敗,請重新檢查是否開啟MySql服務。" + e.Message.ToString()); } } //建立表- create table player() 需要的表頭名字和變數 // public DataSet CreateTable (string name, string[] col, string[] colType) { if (col.Length != colType.Length) // 如果倆陣列不等的時候,丟擲異常 // { throw new Exception ("columns.Length != colType.Length"); } //字串 = create table 名字 (表頭名字 變數)// string query = "CREATE TABLE " + name + " (" + col[0] + " " + colType[0]; for (int i = 1; i < col.Length; ++i) { query += ", " + col[i] + " " + colType[i]; } query += ")"; return ExecuteQuery(query);// 執行查詢(); // } // 建立表,ID自動增長自動縮減 create table player (表頭名字 變數) // public DataSet CreateTableAutoID (string name, string[] col, string[] colType) { if (col.Length != colType.Length) // 如果倆陣列不等的時候,丟擲異常 // { throw new Exception ("columns.Length != colType.Length"); } //字串 = create table 名字 (表頭名字 變數.-------------------------變數不允許為空,自動增值) 第一個是主鍵 // 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 ExecuteQuery(query); } //插入一條資料,包括所有,不適用自動累加ID。--------------------增增增增增增增增增增增增增增增增增增增增// public DataSet InsertInto (string tableName, string[] values) { // 字串-查詢 = insert into lihui.player values('values[0]','values[i]'); // string query = "INSERT INTO " + tableName + " VALUES (" + "'"+ values[0]+ "'"; for (int i = 1; i < values.Length; ++i) { query += ", " + "'"+values[i]+ "'"; } query += ")"; Debug.Log(query); return ExecuteQuery (query); } //插入部分ID public DataSet InsertInto (string tableName, string[] col,string[] values) { if (col.Length != values.Length) { throw new Exception ("columns.Length != colType.Length"); } // 字串-查詢 = insert into lihui.player values('values[0]','values[i]'); // 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 ExecuteQuery (query); } // 查 // public DataSet SelectWhere (string tableName, string[] items, string[] col, string[] operation, string[] values) { if (col.Length != operation.Length || operation.Length != values.Length) { throw new Exception ("col.Length != operation.Length != values.Length"); } // select items[0],intesm[i] from lihui.player where col[0]operation[0]'values[0]'andcol[i]operation[i]'values[0]'; string query = "SELECT " + items[0]; for (int i = 1; i < items.Length; ++i) { query += ", " + items[i]; } if(col.Length == 0) { query += " FROM " + tableName; }else{ query += " FROM " + tableName + " WHERE " + col[0] + operation[0] + "'" + values[0] + "' "; for (int i = 1; i < col.Length; ++i) { query += " AND " + col[i] + operation[i] + "'" + values[0] + "' "; } } Debug.Log(query); return ExecuteQuery (query); } // 改 // 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+" "; Debug.Log(query); return ExecuteQuery (query); } // 刪 // 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 ExecuteQuery (query); } public void Close()// 關閉資料庫連線 // { if(dbConnection != null)// 如果沒有連線 // { dbConnection.Close(); dbConnection.Dispose();//處理// dbConnection = null; } } // 執行查詢,查詢資料庫// public static DataSet ExecuteQuery(string sqlString) { if(dbConnection.State==ConnectionState.Open)// 資料庫成功連線 // { DataSet ds = new DataSet(); try { MySqlDataAdapter da = new MySqlDataAdapter(sqlString, dbConnection); // 把sql穿到資料庫連線裡,讓資料路執行 // da.Fill(ds);// 返回結果 返回一個狀態 用於釋放記憶體// } catch (Exception ee) { throw new Exception("SQL:" + sqlString + "/n" + ee.Message.ToString()); } finally { } return ds; } return null; } // 檢查表是否存在,使用系統資料庫 // public DataSet CheckTable(string tableName) { string query = "SELECT TABLE_NAME from tables where TABLE_NAME = '" + tableName + "'"; return ExecuteSystemQuery (query); } public static DataSet ExecuteSystemQuery(string sqlString) { if(systemDbConnection.State==ConnectionState.Open) { DataSet ds = new DataSet(); try { MySqlDataAdapter da = new MySqlDataAdapter(sqlString, systemDbConnection); da.Fill(ds); } catch (Exception ee) { throw new Exception("SQL:" + sqlString + "/n" + ee.Message.ToString()); } finally { } return ds; } return null; } // 使用正則表示式判斷字串是否為數字型別 // public bool IsNumber(string s) { string pattern = "^[0-9]*$"; Regex rx = new Regex(pattern); return rx.IsMatch(s); } }
using UnityEngine; using System; using System.Data; using System.Collections; using MySql.Data.MySqlClient; using MySql.Data; using System.IO; public class NewBehaviourScript : MonoBehaviour { private DataSet ds; private SqlAccess sql; // 5個輸入框輸入的字元 // public UILabel _ID; public UILabel _Name; public UILabel _QQ; public UILabel _Email; public UILabel _Blog; // button的名字 // public UILabel button_Label; // 預設物體 // public GameObject Prefrab_ID; public GameObject Prefrab_Name; public GameObject Prefrab_QQ; public GameObject Prefrab_Email; public GameObject Prefrab_Blog; public GameObject Prefrab_Button_Changed; public GameObject Prefrab_Button_Delete; public GameObject Prefrab_Plane; public string Error; void Start () { //try //{ sql = new SqlAccess(); Show(); //}catch(Exception e) //{ // Error = e.Message; //} } // 迴圈的方法——顯示資料庫// public void Show(){ float rH = 40f; ds = sql.SelectWhere("momo",new string[]{"id","name","qq","email","blog"},new string [0],new string [0],new string [0]); if(ds != null) { DataTable table = ds.Tables[0]; foreach (DataRow row in table.Rows) { //Plane// //GameObject Plane = Instantiate(Prefrab_Plane,new Vector3 (0f,0f,0f),Quaternion.identity)as GameObject; //Plane.transform.parent = GameObject.FindGameObjectWithTag("Player").transform; // ID列// GameObject ID = Instantiate(Prefrab_ID,new Vector3 (0f,0f,0f),Quaternion.identity)as GameObject; ID.transform.parent=GameObject.FindGameObjectWithTag("Plane").transform; ID.transform.localPosition = new Vector3 (-333f,rH,0f); ID.transform.localScale=new Vector3 (1f,1f,1f); ID .transform.FindChild("Label").GetComponent<UILabel>().text=row["id"].ToString();// 迴圈顯示的資料 // // Name列// GameObject Name = Instantiate(Prefrab_Name,new Vector3 (0f,0f,0f),Quaternion.identity)as GameObject; Name.transform.parent=GameObject.FindGameObjectWithTag("Plane").transform; Name.transform.localPosition = new Vector3 (-234f,rH,0f); Name.transform.localScale=new Vector3 (1f,1f,1f); Name.transform.FindChild("Label").GetComponent<UILabel>().text = row["name"].ToString();// 迴圈顯示的資料 // // QQ列//F GameObject QQ = Instantiate(Prefrab_QQ,new Vector3 (0f,0f,0f),Quaternion.identity)as GameObject; QQ.transform.parent=GameObject.FindGameObjectWithTag("Plane").transform; QQ.transform.localPosition = new Vector3 (-134f,rH,0f); QQ.transform.localScale=new Vector3 (1f,1f,1f); QQ.transform.FindChild("Label").GetComponent<UILabel>().text = row["QQ"].ToString();// 迴圈顯示的資料 // // Email列// GameObject Email = Instantiate(Prefrab_Email,new Vector3 (0f,0f,0f),Quaternion.identity)as GameObject; Email.transform.parent=GameObject.FindGameObjectWithTag("Plane").transform; Email.transform.localPosition = new Vector3 (-34f,rH,0f); Email.transform.localScale=new Vector3 (1f,1f,1f); Email.transform.FindChild("Label").GetComponent<UILabel>().text = row["email"].ToString();// 迴圈顯示的資料 // // Blog列// GameObject Blog = Instantiate(Prefrab_Blog,new Vector3 (0f,0f,0f),Quaternion.identity)as GameObject; Blog.transform.parent=GameObject.FindGameObjectWithTag("Plane").transform; Blog.transform.localPosition = new Vector3 (66f,rH,0f); Blog.transform.localScale=new Vector3 (1f,1f,1f); Blog.transform.FindChild("Label").GetComponent<UILabel>().text = row["blog"].ToString();// 迴圈顯示的資料 // // 改變按鈕// GameObject Button_Changed = Instantiate(Prefrab_Button_Changed,new Vector3 (0f,0f,0f),Quaternion.identity)as GameObject; Button_Changed.transform.parent=GameObject.FindGameObjectWithTag("Plane").transform; Button_Changed.transform.localPosition = new Vector3 (206.9f,rH,0f); Button_Changed.transform.localScale=new Vector3 (1f,1f,1f); Button_Changed.GetComponent<OnClickChanged>().id= row["id"].ToString();// 傳出ID值,到改變按鈕,以便點選使用 // // 刪除按鈕 // GameObject Button_Delete = Instantiate(Prefrab_Button_Delete,new Vector3 (0f,0f,0f),Quaternion.identity)as GameObject; Button_Delete.transform.parent=GameObject.FindGameObjectWithTag("Plane").transform; Button_Delete.transform.localPosition = new Vector3 (304.5f,rH,0f); Button_Delete.transform.localScale=new Vector3 (1f,1f,1f); Button_Delete.GetComponent<OnClickDelete>().ID=row["id"].ToString();// 傳出ID值,到改變按鈕,以便點選使用 // rH+=-50f;// 以間隔為50,遞增行 // } } } // 增 // public void Insert_(){ sql.InsertInto("momo",new string[]{"name","qq","email","blog"},new string[]{_Name.text.ToString(),_QQ.text.ToString(),_Email.text.ToString(),_Blog.text.ToString()}); } // 刪 // public void Delete_(string ID){ sql.Delete("momo",new string []{"id"},new string []{ID} ); } //改// public void Update_(string id_value){ sql.UpdateInto("momo",new string[]{"name","qq","email","blog"},new string[] {_Name.text.ToString(),_QQ.text.ToString(),_Email.text.ToString(),_Blog.text.ToString()},"id",id_value); } //查// public void RequestChangeData(string id) { ds = sql.SelectWhere("momo",new string[]{"id","name","qq","email","blog"},new string []{"id"},new string []{"="},new string []{id}); if(ds != null) { DataTable table = ds.Tables[0]; foreach (DataRow row in table.Rows) { _ID.text = row["id"].ToString(); _Name.text= row["name"].ToString(); _QQ.text = row["qq"].ToString(); _Email.text = row["email"].ToString(); _Blog.text = row["blog"].ToString();// 值顯示的位置 // } } } }
3. 建立NGUI, 如圖,建立相應的Button和Lable等:
4. 在NGUI相應的Button上拖拽相應的程式碼 如圖 : F5
using UnityEngine; using System.Collections; public class F5 : MonoBehaviour { void OnClick(){ // 刪除表,重建表// GameObject[] objs = GameObject.FindGameObjectsWithTag("A"); foreach(GameObject obj in objs){ Destroy(obj); } GameObject.FindGameObjectWithTag("MainCamera").GetComponent<NewBehaviourScript>().Show(); } }
Insert:
using UnityEngine;
using System.Collections;
public class OnClickUpdate : MonoBehaviour {
public UILabel label;
void OnClick(){
if (label.text=="Insert".ToString()){
//Insert,執行程式碼的方法, 清空輸入框 //
GameObject.FindGameObjectWithTag("MainCamera").GetComponent<NewBehaviourScript>().Insert_();
GameObject.FindGameObjectWithTag("MainCamera").GetComponent<NewBehaviourScript>()._ID.text="".ToString();
GameObject.FindGameObjectWithTag("MainCamera").GetComponent<NewBehaviourScript>()._Name.text="".ToString();
GameObject.FindGameObjectWithTag("MainCamera").GetComponent<NewBehaviourScript>()._QQ.text="".ToString();
GameObject.FindGameObjectWithTag("MainCamera").GetComponent<NewBehaviourScript>()._Email.text="".ToString();
GameObject.FindGameObjectWithTag("MainCamera").GetComponent<NewBehaviourScript>()._Blog.text="".ToString();
}
if (label.text=="Update".ToString()){
//Update,執行程式碼的方法,使用提取出來的查詢的ID //
GameObject.FindGameObjectWithTag("MainCamera").GetComponent<NewBehaviourScript>().Update_(GameObject.FindGameObjectWithTag("ID").GetComponent<SrtingID>().idid.ToString());
}
}
}
Reset:
using UnityEngine;
using System.Collections;
public class OnClickReset : MonoBehaviour {
public UILabel name;
void OnClick(){
name.text="Insert".ToString();
GameObject.FindGameObjectWithTag("MainCamera").GetComponent<NewBehaviourScript>()._ID.text="".ToString();
GameObject.FindGameObjectWithTag("MainCamera").GetComponent<NewBehaviourScript>()._Name.text="".ToString();
GameObject.FindGameObjectWithTag("MainCamera").GetComponent<NewBehaviourScript>()._QQ.text="".ToString();
GameObject.FindGameObjectWithTag("MainCamera").GetComponent<NewBehaviourScript>()._Email.text="".ToString();
GameObject.FindGameObjectWithTag("MainCamera").GetComponent<NewBehaviourScript>()._Blog.text="".ToString();
// 點選Update變Insert, 清空輸入框 //
}
}
Delete:
using UnityEngine;
using System.Collections;
public class OnClickDelete : MonoBehaviour {
public string ID;
void OnClick(){
GameObject.FindGameObjectWithTag("MainCamera").GetComponent<NewBehaviourScript>().Delete_(ID);
// 點選刪除 //
}
}
Changed:
using UnityEngine;
using System.Collections;
public class OnClickChanged : MonoBehaviour {
public string id;
void OnClick(){
GameObject.FindGameObjectWithTag("MainCamera").GetComponent<NewBehaviourScript>().button_Label.text="Update".ToString();
GameObject.FindGameObjectWithTag("MainCamera").GetComponent<NewBehaviourScript>().RequestChangeData(id);
GameObject.FindGameObjectWithTag("ID").GetComponent<SrtingID>().idid =id;
// 點選Changed按鈕,Insert變Update,執行程式碼下的查詢的方法,同時把id提取出來方便UpDate使用 //
}
}
按照上面的就OK了。
具體專案原始檔 請回復留下郵箱向我索要。
相關推薦
Unity和MySQL資料庫連線 (一 NGUI形式 )
1. 把下面這個程式碼放在專案檔案裡,無須拖拽到任何物體上。 using UnityEngine; using System; using System.Data; using System.Collections; using MySql.Data.M
MySQL資料庫學習(一)SQL語言基本語法
一、什麼是資料庫 資料庫(Database)是按照資料結構來組織、儲存和管理資料的倉庫。 每個資料庫都有一個或多個不同的API用於建立,訪問,管理,搜尋和複製所儲存的資料。 通常使用關係型資料庫管理系統(RDBMS)來儲存和管理的大資料量。 所謂的關係型資料庫,是建立在關係模
MySQL資料庫總結(一)
概述: 資料庫的作用:通俗易懂的講就是用於資料的儲存。 傳統的儲存方式如文字、Excel等有諸多不足: 文字:檔案過大時開啟會卡頓,非常慢。 Excel:儲存的資料量非常少,不符合當今資料動不動就上百萬條這種海量資料的需求。 資料庫更加方便管理資料,通過sql語句更加
mysql資料庫基礎(一)
一、 表操作 1.建立資料庫 CREATE DATABASE mydb CHARACTER SET utf8; 2.建立資料表 CREATE TABLE IF NOT EXISTS person( person_id SMALLINT UNSIGNED,
Django 建立APP和Mysql資料庫連線
軟體版本:Django 1.11.11 Python:3.7.1 pip3:10.0.1 安裝Django,首先確保python和pip在環境變數中 pip install Django==1.11.11 目錄結構: 其中:settings.py是設定檔案: 例如
MySql資料庫 基礎理論(一)
1 . 什麼是資料庫 資料庫是按照資料結構來組織、儲存和管理資料的倉庫 2. 常見資料庫: Oracle DB2 MySql SQL Server 3. sql是用來操作資料庫的語言 4. 資料庫分為關係型資料庫和非關係型資料庫 5. 資料庫的專業術語RDBMS: 表 table 資料庫 d
javaWeb 簡單註冊登入(含資料庫連線) -- (一)頁面
說在前面: 自己嘗試下寫了這個, 最近web學的東西都在裡面了, 雖然還是很渣, 但也算第一步了, 我姑且算它為一個“專案”, 咳咳 今天剛看到十年前一位學長的畢業設計報告(AOJ評測系統), 只能%%%, 不知道我畢業時能寫出什麼東西來 專案
matlab如何使用jdbc和mysql資料庫連線
1、安裝mysql的驅動包 在已安裝好的mysql資料夾裡找到Connector J 5.1.27這個資料夾下的mysql-connector-java-5.1.27-bin.jar檔案並將其拷貝到matlab的工具箱資料夾中......\MATLAB\R2009a\ja
MySQL資料庫操作(一)——DDL、DML、DCL
MySQL: 啟動:net start mysql 停止:net stop mysql 登入:mysql -u root -p 例如:mysql -uroot -p123 -hlocalh
MySQL資料庫優化(一)
mysql資料庫優化的目的 一 避免網頁訪問錯誤 1資料庫連線timeout產生頁面5xx錯誤 2慢查詢造成頁面無法載入 3阻塞造成資料無法提交 二 增加資料庫的穩定性 三 優化使用者體驗 1流暢的頁面訪問速度 2良好的網站功能體驗 幾個優化方面 硬體-系統配置-資料庫表結
MYSQL資料庫設計(一)
MYSQL資料庫設計 卷首 一個設計精良,結構合理,並且易於維護的資料庫可以大大削減在隨後工作中的一些效能問題,前期做的工作越多,後期做的工作就越少。 思考示例: 假如有一位老師開設了一門課程,對於選擇這門課程的同學需要建立一個數據庫來存放資料,這樣一個數據庫設計時,
mysql資料庫刪除(可用於linux)
由於在9月30號粗暴地打斷了一個匯入程序,今天發現MySQL竟然不能啟動了,只好解除安裝重灌(也許可以花些時間查詢問題,但是這個來的更快些)。重啟匯入程序,卻出現了資料庫已存在的提示資訊。於是就進入命令列
python中操作mysql資料庫CRUD(增刪改查)
python高階應用與資料分析學習筆記 05 1、mysql的安裝 安裝成功是這樣子的 2、pymysql的安裝 一如既往的使用Ancoda來安裝python軟體,
MySQL資料庫分片(分庫分表)
分庫分表 將存放在一個數據庫中的資料,按照特定方式進行拆分,分散到多個數據庫中,已達到分散單臺裝置負載的效果 垂直分割(縱向切分) 水平分割(橫向切分) 將單個表,拆分成多個表,分散到不同的資料庫 將單資料庫的多個表進
C#資料庫連線(4個例子)
PS:轉載自http://www.cnblogs.com/aidd2008/archive/2008/12/05/1348695.html,個人覺得非常不錯,收藏以供學習,若有侵犯權益,請指出 1.C#連線連線Access using System.Data;
docker 安裝MySQL遠端連線(阿里雲伺服器)
1. 下載Mysql的Docker映象:$ docker search mysql (搜尋mysql映象) $ docker pull mysql (下載mysql映象,預設最新版本) 2. 執行映象,設定root賬號初始密碼(123456),對映本地宿主機埠3306到Docker埠3306。測試過程沒有
Jmeter(七) - 從入門到精通 - 建立資料庫測試計劃實戰<MySQL資料庫>(詳解教程)
1.簡介 在實際工作中,我們經常會聽到資料庫的效能和穩定性等等,這些有時候也需要測試工程師去評估和測試,上一篇文章巨集哥主要介紹了jmeter連線和建立資料庫測試計劃的過程,巨集哥在文中通過示例和程式碼非常詳細地介紹給大家,希望對各位小夥伴和童鞋們的學習或者工作具有一定的指導和參考學習價值,遇
如何使用Oracle SQLDeveloper 中連線MS SQLServer和MySQL資料庫(轉)
如何使用Oracle SQLDeveloper 中連線MS SQLServer和MySQL資料庫 一、連線至MySQL資料庫 1.下載mysql的jdbc驅動, [url]http://dev.mysql.com/downloads/[/url] 免費,嘿嘿。 2.解壓zip檔案(我下載
C3P0和dbutils資料庫連線池封裝的使用(一)
首先用資料庫連線池管理Connection,我們就可以重複使用Connection了,有了連線池我們就可以不用自己建立Connection, 然後用完把它歸還給連線池就行了,首先用c3p0資料庫連線池,需要向專案中匯入兩個包:mchange-commons-j
mysql資料庫連線異常問題(總結) mysql資料庫連線異常問題(總結)
mysql資料庫連線異常問題(總結) 1.1 前言 最近專案由1個數據源增加至了3個數據源(連線池使用C3P0),結果各種奇葩的資料庫連線問題接踵而至,為防止將來再次遇到同樣的問題不犯同樣錯誤,現總結如下。 1.2 An attempt by