Unity和MySQL資料庫連線 (一 NGUI形式 )
1. 把下面這個程式碼放在專案檔案裡,無須拖拽到任何物體上。
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了。具體專案原始檔 請回復留下郵箱向我索要。
相關文章
- 連線mysql資料庫MySql資料庫
- 連線資料庫-mysql資料庫MySql
- 用Navicat連線資料庫-資料庫連線(MySQL演示)資料庫MySql
- Unity3d連線SQLServer資料庫Unity3DSQLServer資料庫
- 【MySQL】自定義資料庫連線池和開源資料庫連線池的使用MySql資料庫
- django | 連線mysql資料庫DjangoMySql資料庫
- 如何連線MySQL資料庫MySql資料庫
- pycharm連線MySQL資料庫PyCharmMySql資料庫
- Mysql資料庫表連線MySql資料庫
- PHP連線MySql資料庫PHPMySql資料庫
- mysql資料庫連線(MySQLdb)MySql資料庫
- Weka 連線MySQL資料庫MySql資料庫
- java連線mysql資料庫JavaMySql資料庫
- Ruby連線MySQL資料庫MySql資料庫
- (轉)PHP連線資料庫之PHP連線MYSQL資料庫程式碼PHP資料庫MySql
- Django 2連線MySQL資料庫DjangoMySql資料庫
- mysql資料庫怎麼連線MySql資料庫
- 遠端連線mysql資料庫MySql資料庫
- 【JavaWeb】JDBC連線MySQL資料庫JavaWebJDBCMySql資料庫
- 用thinkphp連線mysql資料庫PHPMySql資料庫
- Python連線MySQL資料庫PythonMySql資料庫
- JDBC連線MySQL資料庫的方法和例項JDBCMySql資料庫
- php基礎之連線mysql資料庫和查詢資料PHPMySql資料庫
- python資料插入連線MySQL資料庫PythonMySql資料庫
- Django使用pymysql連線MySQL資料庫DjangoMySql資料庫
- MySql資料庫連線池專題MySql資料庫
- 使用PETAPOCO連線MYSQL資料庫MySql資料庫
- 精PHP與MYSQL資料庫連線PHPMySql資料庫
- mysql資料庫連線池配置教程MySql資料庫
- PHP連線、查詢MySQL資料庫PHPMySql資料庫
- Pycharm 怎麼連線 MySQL 資料庫PyCharmMySql資料庫
- Spring JPA資料庫連線MySQLSpring資料庫MySql
- 使用ABP EntityFramework連線MySQL資料庫FrameworkMySql資料庫
- R語言連線資料庫(MySQL)R語言資料庫MySql
- MFC 使用VS 連線 MySQL資料庫MySql資料庫
- WAMP無法連線mysql資料庫MySql資料庫
- MySQL 簡潔連線資料庫方式MySql資料庫
- MyGeneration連線MySQL資料庫解決MySql資料庫