利用Unity引擎C#语言实现MySql数据库读写

    本次Demo演示Unity版本:2020.3.25;Visual Studio版本: 2019;MySql.Data.dll版本:5.2.3
    MySql版本:8.0.27

1:导入Unity安装目录下的必要程序集、I18N.CJK、I18N、I18N.West;(因为2020版的Unity默认加载了System.Data.dll,System.Drawing.dll,所以不用再次导入)安装目录路劲为:Editor\Data\MonoBleedingEdge\lib\mono*unityjit*(注意一定是这个目录下的几个程序集,其他的尝试后无效并且报错)
在这里插入图片描述
2:封装的数据库代码:(只写了查询,增删改百度一大堆,基本都能用,重要的是掌握原理)

using System;
using System.Collections;
using System.Collections.Generic;

using MySql.Data.MySqlClient; 

using UnityEngine;

public class MySqlTools 
{
    
    
    string _server, _port,_user, _password, _datename;
    public MySqlTools(string host,string port,string user,string passwd,string database)
    {
    
    
        _server = host;
        _port = port;_user = user;
        _password = passwd;
        _datename = database;
    }
  
    public List<CulQuestionData> Search(string table)//查询,读取数据
    {
    
    
        List<CulQuestionData> questionDatas = new List<CulQuestionData>();
        string connectStr = string.Format("server={0};port={1};user={2};password={3}; database={4};charset=utf8", _server, _port, _user, _password, _datename);//设置连接ip,端口,用户名,密码,以及编码格式 
        MySqlConnection conn = new MySqlConnection(connectStr);//创建连接类
        conn.Open();//正式打开连接 

        string read_sql =string.Format("{0}{1}", "select * from ", table);//sql命令,选择user1表
        MySqlCommand read_cmd = new MySqlCommand(read_sql, conn);
        MySqlDataReader reader = read_cmd.ExecuteReader();

        while (reader.Read())//Read一次就是一行数据,Read不为空执行打印数据
        {
    
    //new List<string> { (string)reader[3], (string)reader[4], (string)reader[5], (string)reader[6] }
            List<string> answer = new List<string>();
            if ((string)reader[3] != "null")
                answer.Add((string)reader[3]);
            if ((string)reader[4] != "null")
                answer.Add((string)reader[4]);
            if ((string)reader[5] != "null")
                answer.Add((string)reader[5]);
            if ((string)reader[6] != "null")
                answer.Add((string)reader[6]);
            CulQuestionData data = new CulQuestionData((int)reader[0], (E_QuestionType)reader[2], (string)reader[1], answer, (string)reader[7]);
            questionDatas.Add(data);
        }
        conn.Close();//关闭连接
        return questionDatas;
    }
}
class ConnDB
{
    
    
    //定义连接地址、端口号、登录用户名、密码、数据库名
    private string server;
    private string port;
    private string user;
    private string password;
    private string datename;

    private MySqlConnection conn;
    //构造函数接收参数
    public ConnDB(string _server, string _port, string _user, string _password, string _datename)
    {
    
    
        this.server = _server;
        this.port = _port;
        this.user = _user;
        this.password = _password;
        this.datename = _datename;
    }
    // 
    /// <summary>
    ///  连接打开数据库
    /// </summary>
    public MySqlConnection openDate()
    {
    
    
        try
        {
    
    
            string connStr = string.Format("server={0};port={1};user={2};password={3}; database={4};", server, port, user, password, datename);
            //连接数据库
            conn = new MySqlConnection(connStr);
            //打开
            conn.Open();
        }
        catch (Exception e)
        {
    
    
            Console.WriteLine("连接数据库错误,原因为:" + e.ToString());
        }
        return conn;
    }
    public void closeDB()
    {
    
    
        //关闭数据库
        conn.Close();
    }
}
 

```csharp
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class GameTest : MonoBehaviour
{
    
    
    public Text text;
    // Start is called before the first frame update
    void Start()
    {
    
    
        ///Config.MYSQL_DATEBASE_NAME  数据库名称
        MySqlTools mySqlTools = new MySqlTools("localhost", "3306", "root", "root", Config.MYSQL_DATEBASE_NAME);
        //自己定义的数据结构
        Config.QUESTIONDATAS = new QuestData(Config.QUEST_TYPE - 1, mySqlTools.Search(Config.MYSQL_TABLES_NAME[Config.QUEST_TYPE - 1]));
        for (int i = 0; i < Config.QUESTIONDATAS._QuestionDatas.Count; i++)
            for (int j = 0; j < Config.QUESTIONDATAS._QuestionDatas[i]._ChooseAnswersItems.Count; j++)
                if (Config.QUESTIONDATAS._QuestionDatas[i]._ChooseAnswersItems[j] == null)
                    Config.QUESTIONDATAS._QuestionDatas[i]._ChooseAnswersItems.RemoveAt(j);
        text.text = "";
        for (int i = 0; i < Config.QUESTIONDATAS._QuestionDatas.Count; i++)
        {
    
    
            print(Config.QUESTIONDATAS._QuestionDatas[i]._IndexQuestion);
            text.text += Config.QUESTIONDATAS._QuestionDatas[i]._IndexQuestion;
        } 
    }

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

在这里插入图片描述
在这里插入图片描述


```csharp
public class CulQuestionData 
{
    
    
    /// <summary>
    /// 当前答题序号
    /// </summary>
    public int _IndexQuestion {
    
     get; set; }
    /// <summary>
    /// 当前答题的类型
    /// </summary>
    public E_QuestionType e_QuestionType {
    
     get; set; }
    public string _Title {
    
     get; set; }
    /// <summary>
    /// 答案选择元素
    /// </summary>
    public List<string> _ChooseAnswersItems {
    
     get; set; }
    /// <summary>
    /// 该题的标准答案 可能有多选
    /// </summary>
    public string _AnswersItems {
    
     get; set; }
    public CulQuestionData(int culIndex, E_QuestionType type, string title, List<string> choiseItems, string answers)
    {
    
    
        _IndexQuestion = culIndex;
        e_QuestionType = type;
        _Title = title;
        _ChooseAnswersItems = choiseItems;
        _AnswersItems = answers;
    }
}

3:配置好自己的数据库:
在这里插入图片描述

MySql.Data.dll 下载地址:https://download.csdn.net/download/qq_41088607/72109351
Demo地址:https://gitee.com/mj516172386/UnityMySQLDemo.git

猜你喜欢

转载自blog.csdn.net/qq_41088607/article/details/122213036