1. 程式人生 > >系列一:Unity資料之SQL增刪改查

系列一:Unity資料之SQL增刪改查

一、
C#編寫的一個數據庫管理類,適用MySQL、MariaDB。
Unity2017.3.1f1 && mariadb-10.0.12-winx64

二、
根據 http://www.w3school.com.cn/sql/index.asp 裡面的語句編寫增刪改查四類方法。(基本語句增刪改查會寫了->高階語句會寫了->其他資料庫語句會寫了。 略略略)

三、
類結構:

  1. 開啟/關閉資料庫
  2. 建立表 (新建,不是覆寫)
  3. 建立id自增表
  4. 插入一行部分值 (不適合id自增表)
  5. 插入一行所有值
  6. 刪除一行
  7. 刪除多行
  8. 刪除所有行
  9. 改變一行某一列
  10. 改變一行某些列
  11. 查詢某一列
  12. 查詢某些列
  13. 查詢所有列
  14. 執行SQL語句

四、
資料庫管理類

/*
*R0-V1.0
*Modify Date:2018-11-27
*Modifier:ZoJet
*Modify Reason:管理資料庫
*Modify Content:
*/
using UnityEngine;
using MySql.Data.MySqlClient;
using System;
using System.Data;

public class SqlManager : MonoBehaviour {
    #region -- 變數定義
    public MySqlConnection sqlConnecter;//聯結器
    public string host = "127.0.0.1";//192.168.1.1  127.0.0.1  localhost

    //與MySQL資料庫對應
    public string db = "test";
    public string id = "root";
    public string password = "root";
    public string port = "3306";
	#endregion

	#region -- 自定義函式
    /// <summary>
    /// 開啟資料庫
    /// </summary>
	public void OpenSql() {
        try {
            string str = string.Format("Host={0};Database={1};User ID={2};Password={3};Port={4}", host, db, id, password, port);
            sqlConnecter = new MySqlConnection(str);
            sqlConnecter.Open();
        } catch(Exception e) {
            throw new Exception(e.Message.ToString());
        }
    }

    /// <summary>
    /// 關閉資料庫
    /// </summary>
    public void CloseSql() {
        if(sqlConnecter != null) {
            sqlConnecter.Close();
            sqlConnecter.Dispose();
            sqlConnecter = null;
        }
    }

    /// <summary>
    /// 執行語句
    /// </summary>
    /// <param name="str"></param>
    /// <returns></returns>
    public DataSet ExcuteStatements(string str) {
        if(sqlConnecter.State == ConnectionState.Open) {
            DataSet dataSet = new DataSet();
            try {
                MySqlDataAdapter mySqlDataAdapter = new MySqlDataAdapter(str, sqlConnecter);
                mySqlDataAdapter.Fill(dataSet);
            } catch (Exception e) {
                throw new Exception(e.Message.ToString());
            } finally { }
            return dataSet;
        }
        return null;
    }

    /// <summary>
    /// 建立表
    /// </summary>
    /// <param name="name">表名</param>
    /// <param name="datas">資料</param>
    /// <param name="types">資料型別</param>
    /// <returns></returns>
    public DataSet CreateTable(string name, string[] datas, string[] types) {
        if(datas.Length != types.Length) {
            throw new Exception("Wrong Input");
        }
        string query = "CREATE TABLE " + name + "(" + datas[0] + " " + types[0];
        for(int i = 1; i < datas.Length; i++) {
            query += "," + datas[i] + " " + types[i];
        }
        query += ")";
        return ExcuteStatements(query);
    }

    /// <summary>
    /// 建立id自增的表
    /// </summary>
    /// <param name="name">表名</param>
    /// <param name="datas">資料</param>
    /// <param name="types">資料型別</param>
    /// <returns></returns>
    public DataSet CreateAutoIDTable(string name,string[] datas,string[] types) {
        if(datas.Length != types.Length) {
            throw new Exception("Wrong Input");
        }
        string query = "CREATE TABLE " + name + "(" + datas[0] + " " + types[0] + " NOT NULL AUTO_INCREMENT";
        for(int i = 1; i < datas.Length; i++) {
            query += ", " + datas[i] + " " + types[i];
        }
        query += ", PRIMARY KEY (" + datas[0] + ")" + ")";
        return ExcuteStatements(query);
    }

    /// <summary>
    /// 插入一行指定列的值(不可用於自增id的表)
    /// INSERT INTO table_name (列1, 列2,...) VALUES (值1, 值2,....)
    /// </summary>
    /// <param name="tableName">表名</param>
    /// <param name="colNames">列名</param>
    /// <param name="colValues">值</param>
    /// <returns></returns>
    public DataSet InsertPartRow(string tableName,string[] colNames,string[] colValues) {
        if(colNames.Length != colValues.Length) {
            throw new Exception("Wrong Input");
        }
        string query = "INSERT INTO " + tableName + " (" + colNames[0];
        for(int i = 1; i < colNames.Length; i++) {
            query += ", " + colNames[i];
        }
        query += ") VALUES (" + "'" + colValues[0] + "'";
        for(int i = 1; i < colValues.Length; i++) {
            query += ", " + "'" + colValues[i] + "'";
        }
        query += ")";
        return ExcuteStatements(query);
    }

    /// <summary>
    /// 插入一行所有列的值
    /// INSERT INTO 表名稱 VALUES (值1, 值2,....)
    /// </summary>
    /// <param name="tableName"></param>
    /// <param name="colName"></param>
    /// <returns></returns>
    public DataSet InsertFullRow(string tableName,string[] colValues) {
        string query = "INSERT INTO " + tableName + " VALUES (" + "'" + colValues[0] + "'";
        for(int i = 1; i < colValues.Length; i++) {
            query += ", " + "'" + colValues[i] + "'";
        }
        query += ")";
        return ExcuteStatements(query);
    }

    /// <summary>
    /// 刪除某一行
    /// DELETE FROM 表名稱 WHERE 列名稱 = 值
    /// </summary>
    /// <param name="tableName"></param>
    /// <param name="colName"></param>
    /// <param name="colValue"></param>
    /// <returns></returns>
    public DataSet DeleteOneRow(string tableName,string colName,string colValue) {
        string query = "DELETE FROM " + tableName + " WHERE " + colName + " = " + "'" + colValue + "'";
        return ExcuteStatements(query);
    }

    /// <summary>
    /// 刪除多行 (滿列則刪除所有行)
    /// DELETE FROM 表名稱 WHERE 列名稱 IN (值1, 值2, ...)
    /// </summary>
    /// <param name="tableName"></param>
    /// <param name="colName"></param>
    /// <param name="colValues"></param>
    /// <returns></returns>
    public DataSet DeleteMultipleRows(string tableName,string colName,string[] colValues) {
        string query = "DELETE FROM " + tableName + " WHERE " + colName + " IN (" + colValues[0];
        for(int i = 1; i < colValues.Length; i++) {
            query += ", " + colValues[i];
        }
        query += ")";
        return ExcuteStatements(query);
    }

    /// <summary>
    /// 刪除所有行
    /// 1. DELETE FROM 表名稱
    /// 2. DELETE * FROM 表名稱
    /// </summary>
    /// <param name="tableName"></param>
    /// <returns></returns>
    public DataSet DeleteAllRows(string tableName) {
        string query = "DELETE FROM " + tableName;
        return ExcuteStatements(query);
    }

    /// <summary>
    /// 更新某一行的一個列
    /// UPDATE 表名稱 SET 列名稱 = 新值 WHERE 列名稱 = 某值
    /// </summary>
    /// <param name="tableName"></param>
    /// <param name="updateColName"></param>
    /// <param name="updateColValue"></param>
    /// <param name="selectColName"></param>
    /// <param name="selectColValue"></param>
    /// <returns></returns>
    public DataSet UpdateOneCol(string tableName,string updateColName,string updateColValue,string selectColName,string selectColValue) {
        string query = "UPDATE " + tableName + " SET " + updateColName + " = " + "'" + updateColValue + "'" + " WHERE " +
            selectColName + " = " + "'" + selectColValue + "'";
        return ExcuteStatements(query);
    }

    /// <summary>
    /// 更新某一行的若干列 (滿列值則更新一整列)
    /// UPDATE 表名稱 SET 列名稱 = 新值 , 列名稱 = 新值 , 列名稱 = 新值 ... WHERE 列名稱 = 某值
    /// </summary>
    /// <param name="tableName"></param>
    /// <param name="updateColNames"></param>
    /// <param name="updateColValues"></param>
    /// <param name="selectColName"></param>
    /// <param name="selectColValue"></param>
    /// <returns></returns>
    public DataSet UpdateMultipleCols(string tableName,string[] updateColNames,string[] updateColValues,string selectColName,string selectColValue) {
        if(updateColNames.Length != updateColValues.Length) {
            throw new Exception("Wrong Input");
        }
        string query = "UPDATE " + tableName + " SET " + updateColNames[0] + " = " + "'" + updateColValues[0] + "'";
        for(int i = 1; i < updateColNames.Length; i++) {
            query += ", " + updateColNames[i] + " = " + "'" + updateColValues[i] + "'";
        }
        query += " WHERE " + selectColName + " = " + "'" + selectColValue + "'";
        return ExcuteStatements(query);
    }

    /// <summary>
    /// 查詢某一列
    /// SELECT 列名稱 FROM表名稱
    /// </summary>
    /// <param name="tableName"></param>
    /// <param name="colName"></param>
    /// <returns></returns>
    public DataSet SelectOneCol(string tableName,string colName) {
        string query = "SELECT " + colName + " FROM " + tableName;
        return ExcuteStatements(query);
    }

    /// <summary>
    /// 查詢多列 (滿列名則查詢整表)
    /// SELECT 列名稱,列名稱... FROM 表名稱
    /// </summary>
    /// <param name="tableName"></param>
    /// <param name="colNames"></param>
    /// <returns></returns>
    public DataSet SelectMultipleCols(string tableName,string[] colNames) {
        string query = "SELECT " + colNames[0];
        for(int i = 1; i < colNames.Length; i++) {
            query += "," + colNames[i];
        }
        query += " FROM " + tableName;
        return ExcuteStatements(query);
    }

    /// <summary>
    /// 查詢整表
    /// SELECT * FROM 表名稱
    /// </summary>
    /// <param name="tableName"></param>
    /// <returns></returns>
    public DataSet SelectAllCols(string tableName) {
        string query = "SELECT * FROM " + tableName;
        return ExcuteStatements(query);
    }
	#endregion
}

五、
DEMO:https://github.com/86K/Data2Database (Test中所有語句測試無誤)
ps : 感謝大佬們打小星星