专栏首页Unity TechnologyJtro的源码分享:封装好的SQLite方法

Jtro的源码分享:封装好的SQLite方法

今天整理了Sql的基本增删改查功能,用在unity中,现在把源码贴出,方便大家查阅与快速开发。

//    脚本功能:封装的数据库方法
//此脚本挂载在: null  上 只能调用使用
//    初创日期:2017.10.24
//        作者:张曙光
//  第一次修改:
using UnityEngine;
using System.Collections;
using Mono.Data.Sqlite;
using System.Collections.Generic;


namespace L_SQL{
/// <summary>
/// 数据库类,基本增删改查方法
/// 可以增删改查 列,表 的方法
/// </summary>
public class SQL{
    
    // 数据库链接对象,通过该对象与数据库文件所在的路径进行链接,进而打开数据库文件
    SqliteConnection con;
    // 数据库文件所在的路径
    string path;
    // 数据库命令
    SqliteCommand command;
    // 数据库读取的信息
    SqliteDataReader reader;

    /// <summary>
    /// 初始化数据库
    /// </summary>
    /// <param name="file"> 需要打开的数据库文件名.sqlite </param>
    public void DataBaseInfo(string file){
        try {
            path="Data Source = " + Application.streamingAssetsPath + "/" + file;
            con = new SqliteConnection (path);
        } catch (System.Exception ex) {
            Debug.Log (ex);
        }

    }

    /// <summary>
    /// 打开数据库
    /// </summary>
    private void OpenDataBase(){
        try {
            con.Open();
            command = con.CreateCommand ();
        } catch (System.Exception ex) {
            Debug.Log (ex);
        }
    }

    /// <summary>
    /// 关闭数据库
    /// </summary>
    private void CloseDataBase(){
        try {
            con.Close ();
            if (command != null) {
                command.Cancel ();
            }
            command = null;
            if (reader != null) {
                reader.Close ();
            }
            reader = null;
        } catch (System.Exception ex) {
            Debug.Log (ex);
        }
    }

    /// <summary>
    /// 基础执行 sql 语句的方法
    /// </summary>
    /// <returns> 返回成功行数 </returns>
    /// <param name="query"> sql语句 </param>
    public int SelectSql(string query){
        OpenDataBase ();
        int count = 0;
        try {
            command.CommandText = query;
            count = command.ExecuteNonQuery ();
        } catch (System.Exception ex) {
            Debug.Log (ex);
        }
        CloseDataBase ();
        return count;
    }

    /// <summary>
    /// 创建一个表,表的常用类型有(TEXT=文本,INTEGER=整数,VARCHAR=字符-需要指定长度 最长255,FLOAT=单精度浮点数,
    /// DOUBLE=双精度浮点数,BOOLEAN=真假)
    /// </summary>
    /// <param name="tableName"> 表格名 </param>
    /// <param name="colNames"> 参数名 </param>
    /// <param name="colTypes"> 参数类型 </param>
    public void CreateTable(string tableName,string[] colNames,string[] colTypes){
        OpenDataBase ();
        string queryString= "create table " + tableName + "(" + colNames[0] + " " + colTypes[0];
        for (int i = 1; i < colNames.Length; i++) {
            queryString += "," + colNames [i] + " " + colTypes [i];
        }
        queryString += ")";
        try {
            command.CommandText = queryString;
            command.ExecuteNonQuery ();
        } catch (System.Exception ex) {
            Debug.Log (ex);
        }
        CloseDataBase ();
    }
    /// <summary>
    /// 向表内插入数据(默认顺序插入)
    /// </summary>
    /// <param name="tableName"> 表名 </param>
    /// <param name="colValues"> 要插入的值 </param>
    public void InsertValues(string tableName,string[] colValues){
        OpenDataBase ();
        string queryString = "INSERT INTO " + tableName + " VALUES ('" + colValues[0];
        for (int i = 1; i < colValues.Length; i++) {
            queryString += "','" + colValues [i];
        }
        queryString += "')";
        try {
            command.CommandText = queryString;
            command.ExecuteNonQuery ();
        } catch (System.Exception ex) {
            Debug.Log (ex);
        }
        CloseDataBase ();
    }
    /// <summary>
    /// 向表内插入数据(按属性名称插入)
    /// </summary>
    /// <param name="tableName"> 表名 </param>
    /// <param name="colNames"> 对应的属性名 </param>
    /// <param name="colValues"> 对应的值 </param>
    public void InsertValues(string tableName,string[] colNames,string[] colValues){
        OpenDataBase ();
        string queryString = "INSERT INTO " + tableName + " (" + colNames[0];
        string queryValues = " VALUES ('" + colValues[0];
        for (int i = 1; i < (colValues.Length <= colNames.Length ? colValues.Length : colNames.Length); i++) {
            queryString += "," + colNames [i];
            queryValues += "','" + colValues [i];
        }
        queryString += ")";
        queryValues += "')";
        queryString += queryValues;
        try {
            command.CommandText = queryString;
            command.ExecuteNonQuery ();
        } catch (System.Exception ex) {
            Debug.Log (ex);
        }
        CloseDataBase ();
    }

    /// <summary>
    /// 查询单个值方法
    /// </summary>
    /// <returns> 返回结果 </returns>
    /// <param name="query"> 输入sql语句 </param>
    public object SelectOneSql(string query){
        OpenDataBase ();
        object obj = new object ();
        try {
            command.CommandText = query;
            obj=command.ExecuteScalar();
        } catch (System.Exception ex) {
            Debug.Log (ex);
        }
        CloseDataBase ();
        return obj;
    } 

    /// <summary>
    /// 输出整个表的内容,用双foreach循环输出即可
    /// </summary>
    /// <returns> 返回表的集合,List表示行,ArrayList表示列元素 </returns>
    /// <param name="tableName"> 表的名称 </param>
    public List<ArrayList> SelectFileSql(string tableName){
        OpenDataBase ();
        List<ArrayList> l = new List<ArrayList> ();
        try {
            command.CommandText = "select * from " + tableName;
            reader=command.ExecuteReader();
            while (reader.Read()) {
                ArrayList temp = new ArrayList ();
                for (int i = 0; i < reader.FieldCount; i++) {
                    temp.Add(reader.GetValue(i));
                }
                l.Add(temp);
            }
            reader.Close();
        } catch (System.Exception ex) {
            Debug.Log (ex);
        }
        CloseDataBase ();
        return l;
    }

    /// <summary>
    /// 查询所有需要值得方法,用双foreach循环输出即可
    /// </summary>
    /// <returns> 返回表的集合,List表示行,ArrayList表示列元素 </returns>
    /// <param name="tableName"> 表的名称 </param>
    /// <param name="colNames"> 所需要输出列的名称 </param>
    public List<ArrayList> SelectFileSql(string tableName,string[] colNames){
        OpenDataBase ();
        string queryString = "select " + colNames [0];
        string queryOper = " from " + tableName;
        for (int i = 1; i < colNames.Length; i++) {
            queryString += "," + colNames [i];
        }
        queryString += " " + queryOper;
        List<ArrayList> l = new List<ArrayList> ();
        try {
            command.CommandText = queryString;
            reader=command.ExecuteReader();
            while (reader.Read()) {
                ArrayList temp = new ArrayList ();
                for (int i = 0; i < reader.FieldCount; i++) {
                    temp.Add(reader.GetValue(i));
                }
                l.Add(temp);
            }
            reader.Close();
        } catch (System.Exception ex) {
            Debug.Log (ex);
        }
        CloseDataBase ();
        return l;
    }

    /// <summary>
    /// 需要判断的查询,用双foreach循环输出即可
    /// </summary>
    /// <returns> 返回表的集合,List表示行,ArrayList表示列元素 </returns>
    /// <param name="tableName"> 表的名称 </param>
    /// <param name="colNames"> 所需要输出列的名称 </param>
    /// <param name="_operator"> where后面的sql判断语句(例如 age>'10',level='20' name like '老%' 之类,别忘单引号),如果不需要条件请输入null </param>
    public List<ArrayList> SelectFileSql(string tableName,string[] colNames,string _operator){
        OpenDataBase ();
        string queryString = "select " + colNames [0];
        string queryOper = " from " + tableName;
        if (_operator!=null) {
            queryOper += " WHERE " + _operator;
        }
        for (int i = 1; i < colNames.Length; i++) {
            queryString += "," + colNames [i];
        }
        queryString += " " + queryOper;
        List<ArrayList> l = new List<ArrayList> ();
        try {
            command.CommandText = queryString;
            reader=command.ExecuteReader();
            while (reader.Read()) {
                ArrayList temp = new ArrayList ();
                for (int i = 0; i < reader.FieldCount; i++) {
                    temp.Add(reader.GetValue(i));
                }
                l.Add(temp);
            }
            reader.Close();
        } catch (System.Exception ex) {
            Debug.Log (ex);
        }
        CloseDataBase ();
        return l;
    }

    /// <summary>
    /// 更新数据的方法
    /// </summary>
    /// <returns> 返回更新成功行数 </returns>
    /// <param name="tableName"> 表名 </param>
    /// <param name="colNames"> 需要修改的列名 </param>
    /// <param name="colNews"> 对应改变的值 </param>
    /// <param name="_operator"> where后面的sql判断语句(例如 age>'10',level='20' name like '老%' 之类,别忘单引号),如果不需要条件请输入null </param>
    public int UpdateFileSql(string tableName,string[] colNames,string[] colNews,string _operator){
        OpenDataBase ();
        string queryOperator = "";
        if (_operator == null) {

        } else {
            queryOperator=" WHERE " + _operator;
        }
        string queryString = "UPDATE " + tableName + " SET " + colNames[0] + "=" + "'" + colNews[0] + "'";
        for (int i = 1; i < colNames.Length; i++) {
            queryString += "," + colNames [i] + "=" + "'" + colNews [i] + "'";
        }
        queryString += queryOperator;
        int count = 0;
        try {
            command.CommandText = queryString;
            count=command.ExecuteNonQuery();
        } catch (System.Exception ex) {
            Debug.Log (ex);
        }
        CloseDataBase ();
        return count;
    }

    /// <summary>
    /// 删除数据的方法
    /// </summary>
    /// <returns> 返回删除成功行数 </returns>
    /// <param name="tableName"> 表名 </param>
    /// <param name="_operator"> where后面的sql判断语句(例如 age>'10',level='20' name like '老%' 之类,别忘单引号),如果不需要条件请输入null </param>
    public int DeleteFileSql(string tableName,string _operator){
        OpenDataBase ();
        string queryOperator = "";
        if (_operator == null) {
            
        } else {
            queryOperator=" WHERE " + _operator;
        }
        string queryString = "DELETE FROM " + tableName + queryOperator;
        int count = 0;
        try {
            command.CommandText = queryString;
            count=command.ExecuteNonQuery();
        } catch (System.Exception ex) {
            Debug.Log (ex);
        }
        CloseDataBase ();
        return count;
    }

    /// <summary>
    /// 更改表名字
    /// </summary>
    /// <param name="tableName"> 需要更改的表 </param>
    /// <param name="newName"> 要改成什么名字 </param>
    public void RenameTable(string tableName,string newName){
        OpenDataBase ();
        try {
            command.CommandText = "ALTER TABLE " + tableName + " RENAME TO " + newName;
            command.ExecuteNonQuery();
        } catch (System.Exception ex) {
            Debug.Log (ex);
        }
        CloseDataBase ();
    }

    /// <summary>
    /// 复制表
    /// </summary>
    /// <param name="tableName"> 被复制表的名称 </param>
    /// <param name="newName"> 复制出的表的名称 </param>
    /// <param name="colNames"> 被复制的列,输入*为完全复制 </param>
    public void CopyTable(string tableName,string newName,string[] colNames){
        OpenDataBase ();
        string queryString = colNames[0];
        for (int i = 1; i < colNames.Length; i++) {
            queryString += "," + colNames [i];
        }
        try {
            command.CommandText = "create table " + newName + " as select " + queryString + " from " + tableName;
            command.ExecuteNonQuery();
        } catch (System.Exception ex) {
            Debug.Log (ex);
        }
        CloseDataBase ();
    }

    /// <summary>
    /// 查询表内所有列名
    /// </summary>
    /// <returns> 返回列名 </returns>
    /// <param name="tableName"> 表名 </param>
    public ArrayList GetListName(string tableName){
        OpenDataBase ();
        ArrayList arr = new ArrayList ();
        try {
            command.CommandText = "select * from " + tableName;
            reader = command.ExecuteReader();
            for (int i = 0; i < reader.FieldCount; i++) {
                arr.Add(reader.GetName(i));
            }
        } catch (System.Exception ex) {
            Debug.Log (ex);
        }
        CloseDataBase ();
        return arr;
    }

    /// <summary>
    /// 查询表内所有列类型
    /// </summary>
    /// <returns> 返回类型 </returns>
    /// <param name="tableName"> 表名 </param>
    public ArrayList GetListType(string tableName){
        OpenDataBase ();
        ArrayList arr = new ArrayList ();
        try {
            command.CommandText = "select * from " + tableName;
            reader = command.ExecuteReader();
            for (int i = 0; i < reader.FieldCount; i++) {
                arr.Add(reader.GetDataTypeName(i));
            }
        } catch (System.Exception ex) {
            Debug.Log (ex);
        }
        CloseDataBase ();
        return arr;
    }

    /// <summary>
    /// 删除整个表格
    /// </summary>
    /// <param name="tableName"> 表名 </param>
    public void DeleteTable(string tableName){
        OpenDataBase ();
        try {
            command.CommandText = "DROP TABLE " + tableName;
            command.ExecuteNonQuery();
        } catch (System.Exception ex) {
            Debug.Log (ex);
        }
        CloseDataBase ();
    }

    /// <summary>
    /// 删除列
    /// </summary>
    /// <param name="tableName"> 表名 </param>
    /// <param name="delListName"> 需要删除的列 </param>
    public void DeleteList(string tableName,string[] delListNames){
        OpenDataBase ();
        ArrayList arr = GetListName (tableName);
        for (int i = 0; i < delListNames.Length; i++) {
            arr.Remove (delListNames[i]);
        }
        string[] str=new string[arr.Count];
        for (int i = 0; i < str.Length; i++) {
            str [i] = arr [i].ToString();
        }
        CopyTable (tableName,"CopyTest",str);
        DeleteTable (tableName);
        RenameTable ("CopyTest",tableName);
        CloseDataBase ();
    }

    /// <summary>
    /// 添加列
    /// </summary>
    /// <param name="tableName"> 表名 </param>
    /// <param name="listName"> 列名 </param>
    /// <param name="listType"> 列类型 </param>
    public void InsertList(string tableName,string listName,string listType){
        OpenDataBase ();
        string queryString = "alter table " + tableName + " add " + listName + " " + listType;
        try {
            command.CommandText = queryString;
            command.ExecuteNonQuery ();
        } catch (System.Exception ex) {
            Debug.Log (ex);
        }
        CloseDataBase ();
    }

    /// <summary>
    /// 更改列名
    /// </summary>
    /// <param name="tableName"> 需要改的表名 </param>
    /// <param name="listName"> 需要改的列名 </param>
    /// <param name="newName"> 新名 </param>
    public void UpdateList(string tableName,string listName,string newName){
        ArrayList arrName = GetListName (tableName);
        ArrayList arrType = GetListType (tableName);
        string[] strName=new string[arrName.Count];
        string[] strType=new string[arrType.Count];
        for (int i = 0; i < arrName.Count; i++) {
            strName [i] = arrName[i].ToString ();
            strType [i] = arrType[i].ToString ();
        }
        for (int i = 0; i < strName.Length; i++) {
            if (strName[i].Equals(listName)) {
                strName [i] = newName;
            }
        }
        CreateTable ("CopyTest",strName,strType);
        string queryString = "insert into CopyTest select * from " + tableName;
        OpenDataBase ();
        try {
            command.CommandText = queryString;
            command.ExecuteNonQuery ();
        } catch (System.Exception ex) {
            Debug.Log (ex);
        }
        CloseDataBase ();
        DeleteTable (tableName);
        RenameTable ("CopyTest",tableName);
    }

}
}

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • Jtro的技术分享:Unity中的文件读写TXT 与XML

    在游戏开发中,有的单机游戏会用到保存数据到本地,或者根据本地的数据来进行下次的设置。这里,鄙人介绍TXT与xml 的读写。 首先是txt: 新建一个unit...

    LittleU
  • Jtro的技术分享:三言两语说反射(unity中使用反射)

    程序集包含模块,而模块包含类型,类型又包含成员。反射则提供了封装程序集、模块和类型的对象。

    LittleU
  • Jtro的技术分享:Unity解析json文件(分为json与jsonArray)

    JSON是一种取代XML的数据结构,和xml相比,它更小巧但描述能力却不差,由于它的小巧所以网络传输数据将减少更多流量从而加快速度,

    LittleU
  • 聊聊rocketmq的MessageQueueSelector

    rocketmq-client-4.5.2-sources.jar!/org/apache/rocketmq/client/producer/MessageQu...

    codecraft
  • 聊聊rocketmq的MessageQueueSelector

    rocketmq-client-4.5.2-sources.jar!/org/apache/rocketmq/client/producer/MessageQu...

    codecraft
  • 如何用agile原则驱动客户体验[DevOps]

    客户体验从未如此重要。只需点击几下鼠标或在手机上进行语音搜索,就可以找到任何信息。他们可以研究产品、服务和公司,可以和世界各地的组织做生意,刷卡购物,一天之内就...

    yyx
  • redis报错 原

    晓歌
  • 通俗易懂设计模式解析——中介者模式

      今天我们一起看看中介者模式,怎么去理解这个模式呢?说起来也简单、好理解。生活中我们租房经常都是通过中介来实现的。一般租房要么是房东直租要么是中介。那么今天要...

    小世界的野孩子
  • MySQL进阶笔记-2(存储引擎)

    最上层是一些客户端和链接服务,包含本地sock 通信和大多数基于客户端/服务端工具实现的类似于 TCP/IP的通信。主要完成一些类似于连接处理、授权认证、及相关...

    千羽
  • 交换友情链接的注意事项

    做外链建设的人都知道友情链接对于网站优化有着重要的作用。在交换友情连接的时候,首先就是要找到合适的网站,了解交换友情链接的条件和要求,在满足双方需求后才能交换。...

    大金SEO

扫码关注云+社区

领取腾讯云代金券