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

这篇博客详细介绍了如何在Unity中使用C#连接和查询MySQL数据库。首先,需要导入必要的程序集,并封装数据库操作类`MySqlTools`和`ConnDB`,用于建立连接和执行SQL查询。然后,在`GameTest`类中调用这些方法从数据库获取数据。博客还提供了MySql.Data.dll的下载链接和一个完整的Unity Demo项目仓库。
摘要由CSDN通过智能技术生成
    本次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

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

有点朦

您的鼓励将是我创作的最大动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值