unity连接mysql数据库

1.首先你需要安装mysql数据库,我装的是最新版的8.0的数据库。没有的可以去这个链接下载
https://dev.mysql.com/downloads/mysql/
2.需要下载mysql.data的动态链接库文件
链接:https://pan.baidu.com/s/1vlVBuUW9k3vNsaCQ-RCHPg
提取码:2zqm
复制这段内容后打开百度网盘手机App,操作更方便哦
3.将动态链接库文件导入unity中
unity连接mysql数据库_第1张图片将选中的5个动态链接库文件导入

在unity的安装目录下有两个动态链接库文件需要导入
D:\unity\2019.1.14f1\Editor\Data\Tools\Roslyn
在这里插入图片描述在这里插入图片描述
4.编写代码测试数据库连接


```csharp
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using MySql.Data.MySqlClient;

public class DataTest : MonoBehaviour
{
	//database代表你要连接的数据库的名字
    private const string datebase = "server=127.0.0.1;user=root;password=123456;database=sms;";
    private MySqlConnection connection = null;
    // Start is called before the first frame update
    void Start()
    {
        connection = new MySqlConnection(datebase);
        connection.Open();
        //查询
        string sql = "select * from admin";
        query(sql);
        //插入
        //sql = "insert into admin values(2,'asdasfsad','1234567',123)";
        //insert(sql);
        //sql = "select * from admin";
        //query(sql);
        //sql = "delete from admin where id = 1";
        //delete(sql);
        sql = "update admin set account = 'dasfsaf' where id = 2";
        updateData(sql);
        sql = "select * from admin";
        query(sql);
        connection.Close();
    }

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

    private void query(string sql)
    {
        MySqlCommand command = new MySqlCommand(sql, connection);
        MySqlDataReader reader = command.ExecuteReader();
        while (reader.Read())
        {
            print("id:" + reader.GetInt32("id") + " account:" + reader.GetString("account") + " password" + reader.GetString("password") + " power" + reader.GetInt32("power"));
        }
        command.Dispose();
    }

    private  void insert(string sql)
    {
        MySqlCommand command = new MySqlCommand(sql, connection);
        int n = command.ExecuteNonQuery();
        if (n > 0)
            print("插入成功");
        else
            print("插入失败");
        command.Dispose();
    }

    private void delete(string sql)
    {
        MySqlCommand command = new MySqlCommand(sql, connection);
        int n = command.ExecuteNonQuery();
        command.Dispose();
    }
    private void updateData(string sql)
    {
        MySqlCommand command = new MySqlCommand(sql, connection);
        int n = command.ExecuteNonQuery();
        command.Dispose();

    }
}


你可能感兴趣的:(unity,mysql,unity3d)