不写博客的我又回来了,很久不见甚是想念,前段时间做开发任务重,现在没事自己研究一些东西,虽然数据库是后端的活,但前端没事也可以学习学习,今天就unity链接MySQL进行一个博客。

准备:

首先准备这些文件:文件会在结尾放到网盘

unity3d怎么连接mysql unity连接数据库能做什么_System

放在Asses\Plugins下

开始:

随后写一个MySQL工具类代码如下:

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

public class MySqlAccess
{
    //连接类对象
    private static MySqlConnection mySqlConnection;
    //IP地址
    private static string host = "127.0.0.1";
    //端口号
    private static string port = "3306";
    //用户名
    private static string userName = "root";
    //密码
    private static string password = "root";
    //数据库名称
    private static string databaseName="database";
    //数据库编码格式 不加此行存时中文会是? 取时取不到数据
    private static string Charset = "utf8"; 

    /// <summary>
    /// 构造方法
    /// </summary>
    public MySqlAccess()
    {
        OpenSql();
    }

    /// <summary>
    /// 打开数据库
    /// </summary>
    public void OpenSql()
    {
        try
        {
            string mySqlString = string.Format("Database={0};Data Source={1};User Id={2};Password={3};port={4};Charset={5}"
                , databaseName, host, userName, password, port, Charset);
            mySqlConnection = new MySqlConnection(mySqlString);
            //if(mySqlConnection.State == ConnectionState.Closed)
            mySqlConnection.Open();

        }
        catch (Exception e)
        {
            throw new Exception("服务器连接失败,请重新检查MySql服务是否打开。" + e.Message.ToString());
        }

    }

    /// <summary>
    /// 关闭数据库
    /// </summary>
    public void CloseSql()
    {
        if (mySqlConnection != null)
        {
            mySqlConnection.Close();
            mySqlConnection.Dispose();
            mySqlConnection = null;
        }
        Debug.Log("已断开数据库");
    }
    /// <summary>
    /// 执行SQL语句
    /// </summary>
    /// <param name="sqlString">sql语句</param>
    /// <returns></returns>
    public DataSet QuerySet(string sqlString)
    {
        Debug.LogWarning(sqlString);
        if (mySqlConnection.State == ConnectionState.Open)
        {
            DataSet ds = new DataSet();
            try
            {
                MySqlDataAdapter mySqlAdapter = new MySqlDataAdapter(sqlString, mySqlConnection);
                mySqlAdapter.Fill(ds);
            }
            catch (Exception e)
            {
                throw new Exception("SQL:" + sqlString + "/n" + e.Message.ToString());
            }
            finally
            {
            }
            return ds;
        }
        return null;
    }
}

 之后我们可以进行sql语句执行工作

增加数据:

数据库怎么建立不再细说,现在只管增加一条数据

数据库表结构如下:

 

unity3d怎么连接mysql unity连接数据库能做什么_git_02

username:用户名

password:密码

userLeave:用户权限等级

现在做数据写入工作 增加一个新用户,代码如下

using System.Collections;
using System.Collections.Generic;
using System.Data;
using UnityEngine;
using UnityEngine.UI;

public class Increase : MonoBehaviour
{
    MySqlAccess mySql;
    public InputField username;
    public InputField password;
    // Start is called before the first frame update
    void Start()
    {
        mySql = new MySqlAccess();
    }
    /// <summary>
    /// 向数据库写入一条数据,此处认为注册一个账号 账号权限等级默认为2
    /// </summary>
    public void IncreaseData()
    {
        mySql.OpenSql();
        DataSet ds = mySql.QuerySet("INSERT INTO user (username,password,userLeave) VALUES ('"+username.text+"','"+password.text+"',2);");
        if (ds != null)
        {
            Debug.Log("录入成功");
        }
        mySql.CloseSql();
    }
}

 unity这边 随便建立两个input field输入框作为账号和密码的记录值 并做一个按钮作为点击事件

unity3d怎么连接mysql unity连接数据库能做什么_c#_03

查询数据

 我们使用刚才建立的账号进行登录工作

仍然是两个input field 一个buttn 作为账号和密码的记录值 并做一个按钮作为点击事件进行登录 代码如下:

using System.Collections;
using System.Collections.Generic;
using System.Data;
using UnityEngine;
using UnityEngine.UI;

public class Login : MonoBehaviour
{
    MySqlAccess mySql;
    public InputField username;
    public InputField password;
    // Start is called before the first frame update
    void Start()
    {
        mySql = new MySqlAccess();
    }
    /// <summary>
    /// 请求登录
    /// </summary>
    public void RequestLogin()
    {
        mySql.OpenSql();
        string loginMsg = "";
        DataSet ds = mySql.QuerySet("Select * FROM USER WHERE `username` = '" + username.text + "' and `password` = '" + password.text + "'");
        if (ds != null)
        {
            DataTable table = ds.Tables[0];
            if (table.Rows.Count > 0)
            {
                loginMsg = "登陆成功!";
                Debug.Log("用户权限等级:" + table.Rows[0][2]);
            }
            else
            {
                loginMsg = "用户名或密码错误!";
                Debug.Log(loginMsg);
            }
        }
        mySql.CloseSql();
    }
}

 修改数据

依旧是是两个input field 一个buttn 作为账号和密码的记录值 并做一个按钮作为点击事件进行修改密码

代码如下:

using System.Collections;
using System.Collections.Generic;
using System.Data;
using UnityEngine;
using UnityEngine.UI;

public class Revise : MonoBehaviour
{
    MySqlAccess mySql;
    public InputField username;
    public InputField password;
    // Start is called before the first frame update
    void Start()
    {
        mySql = new MySqlAccess();
    }
    /// <summary>
    /// 更新用户密码
    /// </summary>
    public void ReviseData()
    {
        mySql.OpenSql();
        DataSet ds = mySql.QuerySet("UPDATE user SET password = '"+password.text+"' WHERE username = '"+username.text+"'");
        if (ds != null)
        {
            Debug.Log("修改密码成功!");
        }
        mySql.CloseSql();
    }
}

删除一条数据

使用一个input field 和一个buttn进行删除工作 

代码如下:

using System.Collections;
using System.Collections.Generic;
using System.Data;
using UnityEngine;
using UnityEngine.UI;

public class Revise : MonoBehaviour
{
    MySqlAccess mySql;
    public InputField username;
    // Start is called before the first frame update
    void Start()
    {
        mySql = new MySqlAccess();
    }
    /// <summary>
    /// 删除一个用户
    /// </summary>
    public void ReviseData()
    {
        mySql.OpenSql();
        DataSet ds = mySql.QuerySet("DELETE FROM user WHERE username = '"+ username.text+ "';");
        if (ds != null)
        {
            Debug.Log("删除用户成功!");
        }
        mySql.CloseSql();
    }
}

至此,数据库增删查改进行完毕,上面都是没加验证,比如删除一个用户时许先查询用户是否存在才能删除,修改密码时验证用户之前旧密码等等验证,可以嵌套进行操作,这里之进行简单的增删查改工作

最后 链接数据库所需文件链接: https://pan.baidu.com/s/1IowbfNGHz_EFMhO5y2uqCA 提取码: qefq 

祝你成功!!