2018-04-19 第一步连接数据库

虽然说unity普遍用sqlite和mysql比较多,但是由于我第一个接触的数据库就是SqlServer,本着先入为主的想法,我查阅了一下网上相关的mysql管理类略作改动,使他可以在SqlServer里运行,下面附上代码。

using UnityEngine;
using System;
using System.Data;
using System.Collections;
using MySql.Data.MySqlClient;
using MySql.Data;
using System.IO;
using System.Data.SqlClient;

public class SqlserverManager
{
    
    static string s = @"server=127.0.0.1;database=DrugDatabase;uid=sa;pwd=123456";
  /*server是你的服务器,不用的话就用本机地址,第二个填你的数据库名称,后面是你的数据库账号密  码,默认是sa/123456*/
    static SqlConnection con = new SqlConnection(s);//数据库连接
    static SqlDataAdapter sda = null;
    static SqlCommand cmd = new SqlCommand();


    public SqlserverManager()
    {

        if (con.State == ConnectionState.Closed)//检测连接是否已经打开,如果没有就打开连接
            OpenSql();
    }


    public static void OpenSql()
    {

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

        }

    }

    public DataSet CreateTable(string name, string[] col, string[] colType)
    {
        if (col.Length != colType.Length)
        {

            throw new Exception("columns.Length != colType.Length");

        }

        string query = "CREATE TABLE " + name + " (" + col[0] + " " + colType[0];

        for (int i = 1; i < col.Length; ++i)
        {

            query += ", " + col[i] + " " + colType[i];

        }

        query += ")";

        return ExecuteQuery(query);
    }

    public DataSet CreateTableAutoID(string name, string[] col, string[] colType)
    {
        if (col.Length != colType.Length)
        {

            throw new Exception("columns.Length != colType.Length");

        }

        string query = "CREATE TABLE " + name + " (" + col[0] + " " + colType[0] + " NOT NULL AUTO_INCREMENT";

        for (int i = 1; i < col.Length; ++i)
        {

            query += ", " + col[i] + " " + colType[i];

        }

        query += ", PRIMARY KEY (" + col[0] + ")" + ")";

        Debug.Log(query);

        return ExecuteQuery(query);
    }

    //插入一条数据,包括所有,不适用自动累加ID。
    public DataSet InsertInto(string tableName, string[] values)
    {

        string query = "INSERT INTO " + tableName + " VALUES (" + "'" + values[0] + "'";

        for (int i = 1; i < values.Length; ++i)
        {

            query += ", " + "'" + values[i] + "'";

        }

        query += ")";

        Debug.Log(query);
        return ExecuteQuery(query);

    }

    //插入部分ID
    public DataSet InsertInto(string tableName, string[] col, string[] values)
    {

        if (col.Length != values.Length)
        {

            throw new Exception("columns.Length != colType.Length");

        }

        string query = "INSERT INTO " + tableName + " (" + col[0];
        for (int i = 1; i < col.Length; ++i)
        {

            query += ", " + col[i];

        }

        query += ") VALUES (" + "'" + values[0] + "'";
        for (int i = 1; i < values.Length; ++i)
        {

            query += ", " + "'" + values[i] + "'";

        }

        query += ")";

        Debug.Log(query);
        return ExecuteQuery(query);

    }

    /// 
    /// 简单查询
    /// 
    /// 表名
    /// 目标列
    /// 约束
    /// 运算符
    /// 约束结果
    /// 
    public DataSet SelectWhere(string tableName, string[] items, string[] col, string[] operation, string[] values)
    {

        if (col.Length != operation.Length || operation.Length != values.Length)
        {

            throw new Exception("col.Length != operation.Length != values.Length");

        }

        string query = "SELECT " + items[0];

        for (int i = 1; i < items.Length; ++i)
        {

            query += ", " + items[i];

        }

        query += " FROM " + tableName + " WHERE " + col[0] + operation[0] + "'" + values[0] + "' ";

        for (int i = 1; i < col.Length; ++i)
        {

            query += " AND " + col[i] + operation[i] + "'" + values[i] + "' ";

        }

        return ExecuteQuery(query);

    }
    /// 
    /// 多表查询
    /// 
    /// 表名
    /// 查询目标
    /// 约束
    /// 运算符
    /// 约束结果
    /// 
    public DataSet SelectWhereFromN(string[] tableName, string[] items, string[] col, string[] operation, string[] values)
    {

        if (col.Length != operation.Length || operation.Length != values.Length)
        {

            throw new Exception("col.Length != operation.Length != values.Length");

        }

        string query = "SELECT " + items[0];

        for (int i = 1; i < items.Length; ++i)
        {

            query += ", " + items[i];

        }

        query += " FROM " + tableName[0];
        for (int i = 1; i < tableName.Length; ++i)
        {

            query += ", " + tableName[i];

        }
        query += " WHERE " + col[0] + operation[0] + "'" + values[0] + "' ";
        for (int i = 1; i < col.Length; ++i)
        {

            query += " AND " + col[i] + operation[i] + "'" + values[i] + "' ";

        }

        return ExecuteQuery(query);

    }
    /// 
    /// 简单修改
    /// 
    /// 表名
    /// 修改前
    /// 修改后
    /// 约束
    /// 约束结果
    /// 
    public DataSet UpdateInto(string tableName, string[] cols, string[] colsvalues, string selectkey, string selectvalue)
    {

        string query = "UPDATE " + tableName + " SET " + cols[0] + " = " + colsvalues[0];

        for (int i = 1; i < colsvalues.Length; ++i)
        {

            query += ", " + cols[i] + " =" + colsvalues[i];
        }

        query += " WHERE " + selectkey + " = " + selectvalue + " ";

        return ExecuteQuery(query);
    }

    public DataSet Delete(string tableName, string[] cols, string[] colsvalues)
    {
        string query = "DELETE FROM " + tableName + " WHERE " + cols[0] + " = " + colsvalues[0];

        for (int i = 1; i < colsvalues.Length; ++i)
        {

            query += " or " + cols[i] + " = " + colsvalues[i];
        }
        Debug.Log(query);
        return ExecuteQuery(query);
    }

    public static void Close()
    {

        con.Close();

    }
//数据库执行部分,颇为重要******
    public static DataSet ExecuteQuery(string sqlString)
    {
        if (con.State == ConnectionState.Open)//检测通道
        {
            DataSet ds = new DataSet();
            try
            {
                sda = new SqlDataAdapter(sqlString, con);
                sda.Fill(ds);
                con.Close();//执行结束关闭通道
            }
            catch (Exception ee)
            {
                throw new Exception("SQL:" + sqlString + "/n" + ee.Message.ToString());
            }
            finally
            {
            }
            return ds;
        }
        return null;
    }


}

然后我们开始简单搭建一下ui;

2018-04-19 第一步连接数据库_第1张图片
image.png

如图,是一个简单的登入界面,值得一提的谁手动选择密码是否显示的部分。下面附上代码

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class InputScript : MonoBehaviour
{

    public Toggle toggle; //ui中的toggle,拖到此处即可
    public InputField input;
    void Start()
    {
        input.contentType = InputField.ContentType.Password;
        toggle.onValueChanged.AddListener(ToggleClick);
    }
    public void ToggleClick(bool isShow)
    {
        input.contentType = isShow ? InputField.ContentType.Standard : InputField.ContentType.Password;
        input.Select();
    }
}

然后我们简单的创建一个用户表


2018-04-19 第一步连接数据库_第2张图片
image.png

然后我们填写登入逻辑(暂时逻辑会不太完全,我还没做错误弹窗部分)

using UnityEngine;
using System;
using System.Data;
using System.Collections;
using MySql.Data.MySqlClient;
using MySql.Data;
using System.IO;
using UnityEngine.UI;
public class LoginBtn : MonoBehaviour
{
    string Error;
    public Text id;
    public InputField password;
    public string userid;
    public int myjurisdiction;
    public GameObject work;
    public GameObject login;
    public void LoginOnClick()
    {
        try
        {

            SqlserverManager sql = new SqlserverManager();
            DataSet ds = sql.SelectWhere("UserTables", new string[] { "password" }, new string[] { "id" }, new string[] { "=" }, new string[] { id.text });
            if (ds != null)
            {
                DataTable table = ds.Tables[0];
                foreach (DataRow row in table.Rows)
                {
                    foreach (DataColumn column in table.Columns)
                    {
                        Debug.Log(row[column]);
                        if(row[column].ToString() == password.text)
                        {
                            Debug.Log("bingo");
                            //跳到工作界面
                            userid = id.text;//日后会用到
                            SqlserverManager sql1 = new SqlserverManager();
                            DataSet ds1 = sql1.SelectWhere("UserTables", new string[] { "Jurisdiction" }, new string[] { "id" }, new string[] { "=" }, new string[] { id.text });
                            if (ds1 != null)
                            {
                                DataTable table1 = ds1.Tables[0];
                                foreach (DataRow row1 in table1.Rows)
                                {
                                    foreach (DataColumn column1 in table1.Columns)
                                    {
                                        Debug.Log(row1[column1]);
                                        myjurisdiction = int.Parse(row1[column1].ToString());//日后会用到
                                    }
                                }
                            }
                            work.SetActive(true);
                            login.SetActive(false);
                        }
                        else
                        {
                            Debug.Log("密码不对");
                            //密码错了
                        }
                    }
                }
                
            }
            else
            {
                Debug.Log("账号不存在");
                //报错窗口
            }
        }
        catch (Exception e)
        {
            Error = e.Message;
        }


    }
    // Update is called once per frame
    void OnGUI()
    {
        if (Error != null)
        {
            GUILayout.Label(Error);
        }

    }
}

你可能感兴趣的:(2018-04-19 第一步连接数据库)