今天来聊聊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);
    }

}
}

正文完