Unity3D 連線MySQL資料庫筆記4-Unity3d程式碼
阿新 • • 發佈:2019-02-19
using UnityEngine; using System; using System.Collections; using System.Data; using MySql.Data.MySqlClient; public class ToMysql : MonoBehaviour { public static MySqlConnection dbConnection; /*mysql資料庫連線物件*/ static string host = ""; static string id = ""; static string pwd = ""; static string database = ""; static string result = ""; private string strCommand ; public static DataSet MyObj; public string connectionString; public Vector2 pPos; public Vector2 pSize; public DataTable pdatatable; public DataSet pDataset; public Vector2 conPos; public Vector2 conSize; void Awake() { host = "127.0.0.1"; /*mysql資料庫伺服器地址*/ id = "root"; /*mysql使用者名稱*/ pwd = "123456"; /*密碼*/ database = "test";/*資料庫名*/ result = ""; /*mysql版本號資訊暫存*/ strCommand = "Select uname from tuser"; /*一些UI按鈕的座標配置資訊11*/ pPos = new Vector2( 50,50 ); pSize = new Vector2(100,35); /*一些UI按鈕的座標配置資訊22*/ conPos = new Vector2( 300,60 ); conSize = new Vector2( 150, 50 ); /*初始給一個新增員工資訊的時候的預設文字框內預設值*/ pkey = "100291"; name = "姓名"; sex = "男"; age = "25"; adress = "家庭詳細住址"; money = "2800"; } void OnGUI() { /*第一次連線到MySQL資料庫*/ ConnectFirstServer(); /*顯示連線到的MySQL資料庫的版本號資訊*/ GUILayout.Label(result); /*主要大列表顯示員工資訊的修改刪除function*/ ShowP_GUIData(); /*新增員工資訊*/ AddPerson(); /*點了修改編輯資訊後*/ ShowEdit_PersonData(); } /*關閉Unity程式*/ public static void OnApplicationQuit() { closeSqlConnection(); } /*第一次連線到MySQL資料庫*/ public void ConnectFirstServer() { if( dbConnection == null ) { GUI.Button( new Rect(conPos.x ,conPos.y,conSize.x,conSize.y),"資料庫Server地址"); host = GUI.TextField(new Rect(conPos.x ,conPos.y+50,conSize.x,conSize.y),host ); GUI.Button( new Rect(conPos.x ,conPos.y+100,conSize.x,conSize.y),"mysql使用者名稱"); id = GUI.TextField(new Rect(conPos.x ,conPos.y+150,conSize.x,conSize.y),id ); GUI.Button( new Rect(conPos.x ,conPos.y+200,conSize.x,conSize.y),"密碼"); pwd = GUI.TextField(new Rect(conPos.x ,conPos.y+250,conSize.x,conSize.y),pwd ); GUI.Button( new Rect(conPos.x ,conPos.y+300,conSize.x,conSize.y),"資料庫名"); database = GUI.TextField(new Rect(conPos.x ,conPos.y+350,conSize.x,conSize.y),database ); connectionString = string.Format("Server = {0};Database = {1}; User = {2}; Password = {3};",host,database,id,pwd); if(GUI.Button(new Rect(conPos.x+180 ,conPos.y+200,conSize.x,conSize.y),"登入資料庫")) { openSqlConnection(connectionString); MyObj = GetDataSet(strCommand); /*讀取資料函式Debug 管理員賬號密碼*/ ReaderData(); /*測試方法Debug 管理員賬號密碼*/ ShowDataSet(); /*重新讀取p_info表裡所有員工資訊*/ SelectPdataSet(); } } } // Connect to database private static void openSqlConnection(string connectionString) { dbConnection = new MySqlConnection(connectionString); try{ dbConnection.Open(); result = dbConnection.ServerVersion; /*獲得MySql的版本*/ } catch(MySqlException e) { Debug.Log( e.Message ); dbConnection = null; host = "伺服器連線錯"; id = "使用者名稱或密碼錯誤"; pwd = "使用者名稱或密碼錯誤"; } Debug.Log(result); } /*關閉Mysql連線*/ private static void closeSqlConnection() { dbConnection.Close(); dbConnection = null; } /*執行某些mysql語句*/ 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 /*得到一個 dataSet物件*/ public DataSet GetDataSet(string sqlString) { DataSet ds = new DataSet(); try { MySqlDataAdapter da = new MySqlDataAdapter(sqlString, dbConnection); da.Fill(ds); } catch (Exception ee) { Debug.Log("SQL:" + sqlString + "\n" + ee.Message.ToString()); dbConnection = null; } return ds; } #endregion /*Debug顯示管理員賬號密碼*/ void ReaderData() { MySqlCommand mySqlCommand = new MySqlCommand("Select * from tuser;", dbConnection); MySqlDataReader reader = mySqlCommand.ExecuteReader(); try { while (reader.Read()) { if (reader.HasRows) { print("uname:" + reader.GetString(0) + "--upwd:" + reader.GetString(1) ); } } } catch (Exception e) { Debug.Log("查詢失敗了!"+ e.Message ); dbConnection = null; } finally { reader.Close(); } } /*Debug顯示管理員賬號密碼*/ void ShowDataSet() { string commandString = "Select * from tuser"; /* 建立DataSet命令物件和DataSet*/ if(dbConnection.State != ConnectionState.Open) { dbConnection = new MySqlConnection(connectionString); try { dbConnection.Open(); result = dbConnection.ServerVersion; /*獲得MySql的版本*/ } catch(MySqlException e) { Debug.Log( e.Message ); dbConnection = null; } } using( MySqlDataAdapter DataAdapter = new MySqlDataAdapter(commandString, connectionString)) { DataSet Dataset = new DataSet(); /* 填充DataSet物件*/ DataAdapter.Fill(Dataset, "tuser"); /*從DataSet獲取一個表*/ DataTable datatable = Dataset.Tables[0]; for (int i = 0; i < datatable.Rows.Count; i++) { Debug.Log( datatable.Rows[i]["uname"].ToString() ); Debug.Log( datatable.Rows[i]["upwd"].ToString() ); } } } /*顯示員工資訊function*/ void SelectPdataSet() { string commandString = "Select * from p_info"; /* 建立DataSet命令物件和DataSet*/ if(dbConnection.State != ConnectionState.Open) { dbConnection = new MySqlConnection(connectionString); try{ dbConnection.Open(); result = dbConnection.ServerVersion; /*獲得MySql的版本*/ } catch(MySqlException e) { Debug.Log( e.Message ); } } using( MySqlDataAdapter DataAdapter = new MySqlDataAdapter(commandString, connectionString)) { if(pDataset !=null ) { pDataset = null; } pDataset = new DataSet(); /* 填充DataSet物件*/ DataAdapter.Fill(pDataset, "p_info"); /*從DataSet獲取一個表*/ if(pdatatable != null) { pdatatable = null; } pdatatable = pDataset.Tables[0]; } } /*主要列表顯示員工資訊的修改刪除function*/ void ShowP_GUIData() { if( pdatatable != null ) { if(pdatatable == null) return; try{ for (int i = 0; i < pdatatable.Rows.Count; i++) { GUI.Button(new Rect(pPos.x ,15 ,pSize.x,pSize.y ), "姓名" ); GUI.Button(new Rect(pPos.x+100 ,15 ,pSize.x,pSize.y ), "性別" ); GUI.Button(new Rect(pPos.x+200 ,15 ,pSize.x,pSize.y ), "年齡" ); GUI.Button(new Rect(pPos.x+300 ,15 ,pSize.x +200,pSize.y ), "家庭詳細住址" ); GUI.Button(new Rect(pPos.x+600,15 ,pSize.x,pSize.y ), "月工資" ); GUI.Button(new Rect(pPos.x ,pPos.y +i*35 ,pSize.x,pSize.y ), pdatatable.Rows[i]["pname"].ToString() ); GUI.Button(new Rect(pPos.x+100 ,pPos.y +i*35 ,pSize.x,pSize.y ), pdatatable.Rows[i]["psex"].ToString() ); GUI.Button(new Rect(pPos.x+200 ,pPos.y +i*35 ,pSize.x,pSize.y ), pdatatable.Rows[i]["page"].ToString() ); GUI.Button(new Rect(pPos.x+300 ,pPos.y +i*35 ,pSize.x +200,pSize.y ), pdatatable.Rows[i]["padress"].ToString() ); GUI.Button(new Rect(pPos.x+600,pPos.y +i*35 ,pSize.x,pSize.y ), pdatatable.Rows[i]["pmoney"].ToString() ); if( GUI.Button(new Rect(pPos.x+710,pPos.y +i*35 ,pSize.x,pSize.y ), "修改" )) { canEdit_person = true; Debug.Log( pdatatable.Rows[i]["pkey"].ToString() ); Edit_Person( pdatatable.Rows[i]["pkey"].ToString() ); pdatatable = null; } if( GUI.Button(new Rect(pPos.x+810,pPos.y +i*35 ,pSize.x,pSize.y ), "刪除" ) ) { DeletePerson( pdatatable.Rows[i]["pkey"].ToString() ); } } if( pdatatable.Rows.Count>=1) { if( GUI.Button(new Rect(pPos.x+750,15 ,pSize.x,pSize.y ), "增加員工資訊" )) { canAddPerson = true; pdatatable = null; } } } catch { Debug.Log( "Some Error"); } } } public string pkey; public string name; public string sex; public string age; public string adress; public string money; public bool canAddPerson; public int selGridInt = 0; public string[] selsex = new string[] {"男", "女"}; public string sqlstr; /*新增員工資訊的function*/ void AddPerson() { if(canAddPerson ) { GUI.Button( new Rect(150 ,conPos.y+100,conSize.x,conSize.y),"員工唯一編號" ); pkey = GUI.TextField(new Rect(conPos.x ,conPos.y+100,conSize.x,conSize.y),pkey ); GUI.Button( new Rect(150 ,conPos.y+160,conSize.x,conSize.y),"姓名" ); name = GUI.TextField(new Rect(conPos.x ,conPos.y+160,conSize.x,conSize.y),name ); GUI.Button( new Rect(150 ,conPos.y+220,conSize.x,conSize.y),"性別" ); selGridInt = GUI.SelectionGrid(new Rect(conPos.x ,conPos.y+220,100,30), selGridInt, selsex, 2); GUI.Button( new Rect(150 ,conPos.y+270,conSize.x,conSize.y),"年齡" ); age = GUI.TextField(new Rect(conPos.x ,conPos.y+270,conSize.x,conSize.y),age ); GUI.Button( new Rect(150 ,conPos.y+330,conSize.x,conSize.y),"家庭詳細住址" ); adress = GUI.TextField(new Rect(conPos.x ,conPos.y+330,conSize.x,conSize.y),adress ); GUI.Button( new Rect(150 ,conPos.y+380,conSize.x,conSize.y),"員工月工資" ); money = GUI.TextField(new Rect(conPos.x ,conPos.y+380,conSize.x,conSize.y),money ); if( GUI.Button(new Rect(conPos.x+280 ,conPos.y+220,conSize.x,conSize.y),"新增此員工資訊") ) { if( pkey.Trim()==""|| name.Trim()==""|| sex.Trim()==""||age.Trim()==""|| adress.Trim()==""||money.Trim()=="") { pkey = "有錯誤請重新輸入"; name = "姓名"; sex = "性別必須為男或女"; age = "年齡必須為數字"; adress = "家庭詳細住址"; money = "月工資必須為數字"; return; } if( selGridInt == 0 ) { sex = "男"; } if( selGridInt == 1 ) { sex = "女"; } if( isNumberic(age)==false && isNumberic(money)==false ) { pkey = "有錯誤請重新輸入"; name = "姓名"; sex = "性別必須為男或女"; age = "年齡必須為數字"; adress = "家庭詳細住址"; money = "月工資必須為數字或超過了限制"; return; } #region /*插入資料*/ try{ openSqlConnection(connectionString); if( dbConnection.State != ConnectionState.Open) { dbConnection.Open(); } sqlstr = string.Format("INSERT INTO p_info(`pkey`, `pname`, `psex`, `page`, `padress`, `pmoney`) VALUES ('{0}','{1}','{2}','{3}','{4}','{5}')", pkey,name,sex,age,adress,money); MySqlCommand cmd = new MySqlCommand(sqlstr, dbConnection); cmd.ExecuteNonQuery(); dbConnection.Close(); Debug.Log("InsertData"); canAddPerson = false; SelectPdataSet(); } catch (MySqlException e){ pkey = "發生錯誤插入失敗"; name = "姓名"; sex = "性別必須為男或女"; age = "年齡必須為數字"; adress = "家庭詳細住址"; money = "月工資必須為數字或超過了限制"; Debug.Log("資訊錄入失敗" + e.Message); } #endregion } if( GUI.Button(new Rect(conPos.x+280 ,conPos.y+320,conSize.x,conSize.y),"返回") ) { canAddPerson = false; SelectPdataSet(); } } } /*檢查輸入的是否是數字*/ public bool isNumberic(string message) { /*判斷是否為整數字符串*/ /*是的話則將其轉換為數字並將其設為out型別的輸出值、返回true, 否則為false*/ int result = -1; /*result 定義*/ try { /*當數字字串的為是少於4時,以下三種都可以轉換,任選一種*/ /*如果位數超過4的話,請選用Convert.ToInt32() 和int.Parse()*/ result = int.Parse(message); return true; } catch { return false; Debug.Log("number false"); } } /*刪除選中員工資訊的方法*/ void DeletePerson(string Spkey) { #region /*刪除資料*/ try{ openSqlConnection(connectionString); if( dbConnection.State != ConnectionState.Open) { dbConnection.Open(); } sqlstr = string.Format("Delete from p_info where pkey='{0}'", Spkey); MySqlCommand cmd = new MySqlCommand(sqlstr, dbConnection); cmd.ExecuteNonQuery(); dbConnection.Close(); Debug.Log("DeleteData"); SelectPdataSet(); } catch (MySqlException e){ Debug.Log("刪除失敗" + e.Message); } #endregion } public bool canEdit_person; /*傳入選中要修改員工的主鍵pkey,並讀取出對應資料給多個欄位*/ void Edit_Person( string mpkey ) { if(canEdit_person) { #region 檢索當前選中的資料 string commandString5 = string.Format("Select * from p_info where pkey='{0}'", mpkey); Debug.Log( commandString5); /* 建立DataSet命令物件和DataSet*/ if(dbConnection.State != ConnectionState.Open) { dbConnection = new MySqlConnection(connectionString); try { dbConnection.Open(); result = dbConnection.ServerVersion; /*獲得MySql的版本*/ } catch(MySqlException e) { Debug.Log( e.Message ); } } using( MySqlDataAdapter DataAdapter = new MySqlDataAdapter(commandString5, connectionString)) { DataSet spDataset = new DataSet(); /* 填充DataSet物件*/ DataAdapter.Fill(spDataset, "p_info"); /*從DataSet獲取一個表*/ DataTable spdatatable = spDataset.Tables[0]; pkey= spdatatable.Rows[0]["pkey"].ToString() ; name = spdatatable.Rows[0]["pname"].ToString() ; age =spdatatable.Rows[0]["page"].ToString() ; adress= spdatatable.Rows[0]["padress"].ToString() ; money=spdatatable.Rows[0]["pmoney"].ToString() ; } #endregion } } /*點選修改資料按鈕後,詳細顯示當前選中的員工的資訊,並提供文字框進行修改*/ void ShowEdit_PersonData() { if(canEdit_person) { /* GUI.Button( new Rect(150 ,conPos.y+100,conSize.x,conSize.y),"員工唯一編號" ); pkey = GUI.TextField(new Rect(conPos.x ,conPos.y+100,conSize.x,conSize.y),pkey ); */ GUI.Button( new Rect(150 ,conPos.y+160,conSize.x,conSize.y),"姓名" ); name = GUI.TextField(new Rect(conPos.x ,conPos.y+160,conSize.x,conSize.y),name ); GUI.Button( new Rect(150 ,conPos.y+220,conSize.x,conSize.y),"性別" ); selGridInt = GUI.SelectionGrid(new Rect(conPos.x ,conPos.y+220,100,30), selGridInt, selsex, 2); GUI.Button( new Rect(150 ,conPos.y+270,conSize.x,conSize.y),"年齡" ); age = GUI.TextField(new Rect(conPos.x ,conPos.y+270,conSize.x,conSize.y),age ); GUI.Button( new Rect(150 ,conPos.y+330,conSize.x,conSize.y),"家庭詳細住址" ); adress = GUI.TextField(new Rect(conPos.x ,conPos.y+330,conSize.x,conSize.y),adress ); GUI.Button( new Rect(150 ,conPos.y+380,conSize.x,conSize.y),"員工月工資" ); money = GUI.TextField(new Rect(conPos.x ,conPos.y+380,conSize.x,conSize.y),money ); Debug.Log("EditPersonData"); if( GUI.Button(new Rect(conPos.x+280 ,conPos.y+220,conSize.x,conSize.y),"返回主頁") ) { canEdit_person = false; SelectPdataSet(); } if( GUI.Button(new Rect(conPos.x+280 ,conPos.y+320,conSize.x,conSize.y),"修改員工資訊") ) { if( pkey.Trim()==""|| name.Trim()==""|| sex.Trim()==""||age.Trim()==""|| adress.Trim()==""||money.Trim()=="") { pkey = "有錯誤請重新輸入"; name = "姓名"; sex = "性別必須為男或女"; age = "年齡必須為數字"; adress = "家庭詳細住址"; money = "月工資必須為數字"; return; } if( selGridInt == 0 ) { sex = "男"; } if( selGridInt == 1 ) { sex = "女"; } if( isNumberic(age)==false && isNumberic(money)==false ) { pkey = "有錯誤請重新輸入"; name = "姓名"; sex = "性別必須為男或女"; age = "年齡必須為數字"; adress = "家庭詳細住址"; money = "月工資必須為數字或超過了限制"; return; } #region /*更新資料*/ try{ openSqlConnection(connectionString); if( dbConnection.State != ConnectionState.Open) { dbConnection.Open(); } sqlstr = string.Format("UPDATE p_info SET pname='{0}', psex='{1}', page='{2}', padress='{3}', pmoney='{4}'WHERE pkey = '{5}'", name,sex,age,adress,money ,pkey); MySqlCommand cmd = new MySqlCommand(sqlstr, dbConnection); cmd.ExecuteNonQuery(); dbConnection.Close(); Debug.Log("UpdateData"); canEdit_person = false; SelectPdataSet(); } catch (MySqlException e){ pkey = "發生錯誤更新失敗"; name = "姓名"; sex = "性別必須為男或女"; age = "年齡必須為數字"; adress = "家庭詳細住址"; money = "月工資必須為數字或超過了限制"; Debug.Log("資訊錄入失敗" + e.Message); } #endregion } } } }