unity and MySql

來源:互聯網
上載者:User

標籤:

摘要:資料庫的圖片以及內容

1.資料庫的封裝

using System;
using System.Linq;
using System.Data;
using UnityEngine;
using System.Text;
using System.Collections.Generic;
using MySql.Data.MySqlClient;

 

public class SqlAccess
{
    public static MySqlConnection dbConnection;
    //如果只是在本地的話,寫localhost就可以。
    // static string host = "localhost"; 
    //如果是區域網路,那麼寫上原生區域網路IP
    static string host = "localhost";
    static string id = "root";//可以通過這個使用者訪問資料庫
    static string pwd = "013287";//建立連結時候的密碼
    static string database = "man";//資料庫的名字

    public SqlAccess()
    {
        OpenSql();
    }

    public static void OpenSql()
    {

        try
        {
            string connectionString = string.Format("Server = {0};port={4};Database = {1}; User ID = {2}; Password = {3};", host, database, id, pwd, "3306");//連結資料庫的欄位
            dbConnection = new MySqlConnection(connectionString);
            dbConnection.Open();
        }
        catch (Exception e)
        {
            throw new Exception("伺服器串連失敗,請重新檢查是否開啟MySql服務。" + e.Message.ToString());

        }

    }

    public DataSet CreateTable(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];

        for (int i = 1; i < col.Length; ++i)
        {

            query += ", " + col[i] + " " + colType[i];

        }

        query += ")";

        return ExecuteQuery(query);
    }

    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 ExecuteQuery(query);
    }

    //插入一條資料,包括所有,不適用自動累加ID。
    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 ExecuteQuery(query);

    }

    //插入部分ID
    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 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");

        }

        string query = "SELECT " + items[0];

        for (int i = 1; i < items.Length; ++i)
        {

            query += ", " + items[i];

        }

        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] + "‘ ";

        }

        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 + " ";

        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); //把修改好的資料通過適配器改回資料庫,及修改資料庫
                da.Fill(ds);

            }
            catch (Exception ee)
            {
                throw new Exception("SQL:" + sqlString + "/n" + ee.Message.ToString());
            }
            finally
            {
            }
            return ds;
        }
        return null;
    }
}

2.資料庫與unity的連結

這個指令碼需要掛載在一個啟用的物體上

using System;
using UnityEngine;
using System.Data;
using System.Collections;

public class NewBehaviourScript : MonoBehaviour {

    string Error = null;
    void Start()
    {
        try
        {

            SqlAccess sql = new SqlAccess(); //擷取對封裝好的資料庫的引用

            //   sql.CreateTableAutoID("people", new string[] { "idcard", "age", "name" }, new string[] {  "idcard", "age", "name"});
            //sql.CreateTable("momo",new string[]{"name","qq","email","blog"}, new string[]{"text","text","text","text"});
            // sql.InsertInto("people", new string[] { "idcard", "age", "name" }, new string[] { "6789", "22", "qiang" });
            //  sql.InsertInto("people", new string[] { "idcard", "age", "name"}, new string[] { "5", "age2", "name2" });

            DataSet ds = sql.SelectWhere("people", new string[] { "idcard", "age", "name" }, new string[] { "idcard" }, new string[] { "=" }, new string[] { "520" }); //把返回的資料集付給ds,此時的修改已經在封裝好的sqlAccess中改回資料庫了,此時通過ds進行UI顯示或輸出等
            if (ds != null)
            {

                DataTable table = ds.Tables[0];

                foreach (DataRow row in table.Rows)
                {
                    foreach (DataColumn column in table.Columns)
                    {
                        Debug.Log(row[column]);
                    }
                }
            }
            sql.Close();
        }
        catch (Exception e)
        {
            Error = e.Message;
        }

    }

    // Update is called once per frame
    void OnGUI()
    {

        if (Error != null)
        {
            GUILayout.Label(Error);
        }

    }
}

unity and MySql

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.