Unity3D实现MySql数据库登录与注册功能

一、搭建测试界面

1、界面布局如下:
在这里插入图片描述
2、界面控件
在这里插入图片描述

二、代码实现

1、封装MySql

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using MySql.Data.MySqlClient;
using UnityEngine.Events;
using System.Data;
/// <summary>
/// MySql工具类
/// </summary>
public class MySqlTool
{
    /// <summary>
    /// 单例
    /// </summary>
    public static MySqlTool Instance;
    /// <summary>
    /// 路径
    /// </summary>
    public static string conPath = "Database=testdatabase;datasource=localhost;port=3306;user=root;password=123456;";
    /// <summary>
    /// 连接实例
    /// </summary>
    public static MySqlConnection con;
    /// <summary>
    /// 获取MySqlTool工具实例
    /// </summary>
    /// <returns></returns>
    public static MySqlTool GetInstance()
    {
        if(Instance==null)  
            Instance = new MySqlTool();
        return Instance;
    }
    /// <summary>
    /// 初始化时打开数据库
    /// </summary>
    public MySqlTool()
    {
        GetConnect();
    }
    /// <summary>
    /// 获取连接实例
    /// </summary>
    public void GetConnect()
    {
        try
        {
            if(con.State!=ConnectionState.Open)
            {
                con.Open();
            }     
        }
        catch(System.Exception e)
        {
            Debug.Log("服务器打开失败:"+e.Message.ToString());//有错则报出错误
        }    
    }
    /// <summary>
    /// 关闭连接
    /// </summary>
    private void Close()
    {
        if(con!=null)
        {
            con.Close();
        }
    }
    /// <summary>
    /// 获取数据读取实例
    /// </summary>
    public MySqlDataReader GetReader(string tableName)
    {
        GetConnect();
        try
        {
            string selectStatement = "select*from " + tableName;
            MySqlCommand cmd = new MySqlCommand(selectStatement,con);
            MySqlDataReader reader = cmd.ExecuteReader();
            return reader;
        }
        catch (System.Exception e)
        {
            Debug.Log("错误:"+e.Message.ToString());
            return null;
        }   
    }
    /// <summary>
    /// 执行Sql语句
    /// </summary>
    /// <param name="com"></param>
    private void ExecuteSql(string sqlCom)
    {
        GetConnect();
        try
        {
            MySqlCommand cmd = new MySqlCommand(sqlCom,con);
            cmd.ExecuteNonQuery();
        }
        catch (System.Exception e)
        {
            Debug.Log("错误:"+e.Message.ToString());
        }
        finally
        {
            Close();
        }
    }
    /// <summary>
    /// 插入新用户
    /// </summary>
    /// <param name="tableName">表名</param>
    /// <param name="userName">新的用户名</param>
    /// <param name="password">新密码</param>
    public void InsertUser(string tableName,string userName,string password)
    {
        string connstr = "insert into " + tableName + "(userName,password) values ('" + userName + "','" + password + "')";
        ExecuteSql(connstr);
    }
    }

2、编写登录、注册功能脚本

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using MySql.Data.MySqlClient;
/// <summary>
/// 登录注册页
/// </summary>
public class LoginPanel : MonoBehaviour
{
    /// <summary>
    /// 姓名、密码
    /// </summary>
    public InputField nameInput, passwordInput;
    /// <summary>
    /// 登录、注册、确定登录、确定注册
    /// </summary>
    public Button loginBtn, registerBtn, sureLoginBtn, sureRegisterBtn;
    /// <summary>
    /// 用户信息(名字、密码)字典
    /// </summary>
    private Dictionary<string, string> userDic = new Dictionary<string, string>();
    /// <summary>
    /// 数据读取实例
    /// </summary>
    private MySqlDataReader reader;
    void Start()
    {
        //按钮添加监听
        loginBtn.onClick.AddListener(delegate 
        {
            sureLoginBtn.gameObject.SetActive(true);
            sureRegisterBtn.gameObject.SetActive(false);
        });
        registerBtn.onClick.AddListener(delegate 
        {
            sureRegisterBtn.gameObject.SetActive(true);
            sureLoginBtn.gameObject.SetActive(false);
        });
        sureLoginBtn.onClick.AddListener(delegate 
        {
            OnLogin(nameInput.text,passwordInput.text);
        });
        sureRegisterBtn.onClick.AddListener(delegate
        {
            OnRegister(nameInput.text, passwordInput.text);
        });
    }
    /// <summary>
    /// 读取用户表中的数据
    /// </summary>
    private void ReadUserTable()
    {
        userDic.Clear();
        reader = MySqlTool.Instance.GetReader("user");//user为用户表名
        while(reader.Read())
        {
            string userName = reader.GetString("userName");//userName为user表中的姓名字段
            string password = reader.GetString("password");//password为user表中的密码字段
            userDic.Add(userName,password);
        }
        reader.Close();
    }
    /// <summary>
    /// 登录
    /// </summary>
    /// <param name="inputName">输入的用户名</param>
    /// <param name="inputPassword">输入的密码</param>
    private void OnLogin(string inputName,string inputPassword)
    {
        ReadUserTable();
        if(userDic.ContainsKey(inputName))
        {
            string value;
            if(userDic.TryGetValue(inputName,out value))
            {
                      if(value==inputPassword)
                      {
                      Debug.Log("登成功!");
                      }
                
            }
            else
            {
                Debug.Log("密码错误!");
            }
        }
        else
        {
            Debug.Log("用户名不存在!");
        }
    }
    /// <summary>
    /// 注册
    /// </summary>
    /// <param name="inputName">输入的用户名</param>
    /// <param name="inputPassword">输入的密码</param>
    private void OnRegister(string inputName, string inputPassword)
    {
        ReadUserTable();
        if (userDic.ContainsKey(inputName))
        {
            Debug.Log("用户已存在!");
        }
        else
        {
            MySqlTool.GetInstance().InsertUser("user", inputName,inputPassword);
            Debug.Log("用户注册成功!");
        }
    }
}

三、属性映射关系

挂载LoginPanel脚本,并将控件映射到公共属性如下:

在这里插入图片描述

四、运行测试

有问题请指出,谢谢!

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
THE END
分享
二维码
< <上一篇
下一篇>>