Unity 连接 sqlserver

通过连接sqlserver,来获取上面的用户名密码,来验证进入软件

首先我先用VS编了一个连接数据库的dll,编写dll的时候要注意的是要把目标框架改为.Net Framework 3.5,不然导入Unity会报错。

using System;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Collections.Generic;
using UnityEngine;
namespace SqlReader
{
	public static class SqlRead
	{
		static SqlConnection sqlcon = new SqlConnection("server=ip地址;database=数据库名称;uid=用户名;pwd=密码");
		static SqlCommand cmd = new SqlCommand();
		public static Dictionary<string, string> Read(string CommandText)
		{
			Dictionary<string, string> _dic = new Dictionary<string, string>();
			try
			{
				//sqlcon.Open();
				cmd.Connection = sqlcon;
				cmd.CommandType = System.Data.CommandType.Text;
				cmd.CommandText = CommandText; // 因为我的数据库里面只有一条数据,所以这里就这么写了
				sqlcon.Open();
				SqlDataReader dr = cmd.ExecuteReader();
				while (dr.Read())
				{
					_dic.Add(dr["UserName"].ToString(), dr["Password"].ToString());
				}
				dr.Close();
				cmd.Connection.Close();
				sqlcon.Close();
				sqlcon.Dispose();
			}
			catch (System.Exception e)
			{
				Debug.LogError(e);
			}
			return _dic;
		}
	}

}
编译后得到SqlReader.dll,在bin/Debug里面,把他移动到Unity中

unity中的使用代码

using System.Collections.Generic;
using SqlReader;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

public class GameAuth : MonoBehaviour {
	Dictionary<string,string> usernamepsw = new Dictionary<string, string>();
    // Use this for initialization
    void Start ()
    {
		usernamepsw = SqlRead.Read("select * from GameAuthority");
        //foreach (var VARIABLE in usernamepsw)
        //{
            
        //}
        bool a = false;
    }

    public InputField username;
    public InputField password;

    public void login()
    {
        StartCoroutine(checkNet());
    }

    IEnumerator checkNet()
    {
        int readcount = 0;
        while (usernamepsw.Count<=0&&readcount<=3)
        {
            usernamepsw = SqlRead.Read("select * from GameAuthority");
            readcount++;
            yield return new WaitForSeconds(0.5f);
        }
        if (usernamepsw.Count==0)
        {
            Debug.LogError("网络不可用");
            yield break;
        }
        if (username.text == "")
        {
            Debug.LogError("用户名不能为空");
            yield break;
        }
        if (!isExist(username.text))
        {
            Debug.LogError("用户名错误");
            yield break; 
        }
        if (usernamepsw[username.text] != password.text)
        {
            Debug.LogError("密码错误");
            yield break;
        }
        SceneManager.LoadScene(1);
    }
    public bool isExist(string username)
    {
        foreach (var val in usernamepsw)
        {
            if (val.Key==username)
            {
                return true;
            }
        }
        return false;
    }
}

在编译器中这是可以用的,但是输出后就无法连接了,这是因为还需要3个dll,在unity安装 目录 \Editor\Data\Mono\lib\mono\unity中,

I18N.dll,I18N.West.dll,I18N.CJK.dll

把这三个dll放到Assets下就行了

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页