Unity SqlServer数据库数据的读取与解析

该博客介绍了如何在Unity3D中与SQL Server数据库进行交互,包括连接配置、数据读取、数据写入和数据查找操作。通过使用SqlConnection、SqlDataAdapter等.NET库,实现了对数据库的增删查改功能,主要用于窗口配置信息的管理。
摘要由CSDN通过智能技术生成
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using UnityEngine;

/// <summary>
/// SqlServer数据库数据的读取与解析
/// </summary>
public class SqlServerConfigParse : MonoBehaviour
{
    public static SqlServerConfigParse instance;

    public bool canConnectSqlServer = false;

    SqlConnection connection = null;

    SqlDataAdapter dataAdapter = null;

    #region 操作语句
    string connectStr = "server={0};database={1};uid={2};pwd={3}";

    string insert_Browser = "INSERT INTO FangZhen_Browser(BrowserName,X,Y,Width,Height,url,StationID,SceneModeIndex) VALUES('{0}',{1},{2},{3},{4},'{5}','{6}',{7})";

    string update_Browser = "Update FangZhen_Browser set X={0},Y={1},Width={2},Height={3},url='{4}',StationID='{5}',SceneModeIndex={6} where BrowserName='{7}'";

    string delet_Browser = "Delete from FangZhen_Browser where BrowserName='{0}'";

    string findStr = "select * from {0}";

    string findRowStr = "SELECT * FROM {0} WHERE BrowserName='{1}'";
    #endregion

    private void Awake()
    {
        instance = this;

        InitConnection();
    }

    void InitConnection()
    {
        DataBaseConfig config = JsonConfigParse.GetDataBaseConfigByJson();

        if (!ConfigurationData.IsPingAimIP(config.IP))
        {
            canConnectSqlServer = false;
            return;
        }

        connectStr = string.Format(ConfigurationData.configSqlConnectionStr, config.IP, config.database, config.uid, config.pwd);

        connection = new SqlConnection(connectStr);

        try
        {
            connection.Open();

            canConnectSqlServer = true;
        }
        catch (System.Exception)
        {
            canConnectSqlServer = false;
            throw;
        }
    }

    #region 数据读取
    /// <summary>
    /// 获取窗口配置信息
    /// </summary>
    /// <returns></returns>
    public List<BrowserConfig> GetBrowserMsgFromSqlServer()
    {
        List<BrowserConfig> MsgDic = new List<BrowserConfig>();

        string sql = "select * from FangZhen_Browser";

        dataAdapter = new SqlDataAdapter(sql, connection);

        DataTable dt = new DataTable();

        dataAdapter.Fill(dt);

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            BrowserConfig browserMsg = new BrowserConfig
            {
                BrowserName = dt.Rows[i]["BrowserName"].ToString(),
                X = float.Parse(dt.Rows[i]["X"].ToString()),
                Y = float.Parse(dt.Rows[i]["Y"].ToString()),
                Width = float.Parse(dt.Rows[i]["Width"].ToString()),
                Height = float.Parse(dt.Rows[i]["Height"].ToString()),
                Url = dt.Rows[i]["url"].ToString(),
                StationID = dt.Rows[i]["StationID"].ToString(),
                SceneModeIndex = int.Parse(dt.Rows[i]["SceneModeIndex"].ToString())
            };

            if (!MsgDic.Contains(browserMsg))
            {
                MsgDic.Add(browserMsg);
            }
        }

        connection.Close();

        return MsgDic;
    }
    #endregion

    #region 数组写入
    /// <summary>
    /// 更新窗口表
    /// </summary>
    /// <param name="browsers"></param>
    public void UpdateBrowserForSqlServer(BrowserConfig browser)
    {
        SqlCommand cmd = new SqlCommand();

        if (connection.State == ConnectionState.Closed)
        {
            connection.Open();
        }

        //查询表中是否已存在此名称窗口
        string sql = string.Format(findRowStr, "FangZhen_Browser", browser.BrowserName);

        dataAdapter = new SqlDataAdapter(sql, connection);

        DataTable dt = new DataTable();

        dataAdapter.Fill(dt);

        //存在,更新窗口
        if (dt.Rows.Count != 0)
        {
            cmd.CommandText = string.Format(update_Browser, browser.X, browser.Y, browser.Width,
                browser.Height, browser.Url, browser.StationID, browser.SceneModeIndex, browser.BrowserName);
        }
        //不存在,添加窗口
        else
        {
            cmd.CommandText = string.Format(insert_Browser, browser.BrowserName, browser.X, browser.Y,
            browser.Width, browser.Height, browser.Url, browser.StationID, browser.SceneModeIndex);
        }

        cmd.Connection = connection;

        cmd.ExecuteNonQuery();

        connection.Close();
    }

    /// <summary>
    /// 删除窗口表中的指定元素
    /// </summary>
    /// <param name="browser"></param>
    public void DeletBrowserFromSqlServer(string browserName)
    {
        SqlCommand cmd = new SqlCommand();

        if (connection.State == ConnectionState.Closed)
        {
            connection.Open();
        }

        cmd.Connection = connection;

        cmd.CommandText = string.Format(delet_Browser, browserName);

        cmd.ExecuteNonQuery();

        connection.Close();
    }
    #endregion

    #region 数据查找
    public BrowserConfig Select(string n)//查找数据 并返回
    {
        BrowserConfig data = null;
        using (connection)
        {
            try
            {
                //表示一个Sql 这里指向Conn的存储过程
                SqlCommand select = new SqlCommand("select * from FangZhen_Browser where BrowserName='" + n + "'", connection);
                SqlDataReader sr = select.ExecuteReader(); // 使用上面的语句查询数据库
                while (sr.Read()) // 读取数据
                    data = new BrowserConfig
                    {
                        BrowserName = sr["BrowserName"].ToString(),
                        X = float.Parse(sr["X"].ToString()),
                        Y = float.Parse(sr["Y"].ToString()),
                        Width = float.Parse(sr["Width"].ToString()),
                        Height = float.Parse(sr["Height"].ToString()),
                        Url = sr["url"].ToString(),
                        StationID = sr["StationID"].ToString(),
                        SceneModeIndex = int.Parse(sr["url"].ToString())
                    }; //类似于字典的操作

                Debug.Log(data.BrowserName);
            }
            catch (SqlException ex)
            {
                Debug.LogError(ex.Message);
            }
        }
        return data;
    }
    #endregion
}

 

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值