Unity2020 使用SQLite (添/删/改/查)(保姆级)

资源下载

项目资源

Unity版本   Unity 2020.3.26f1c1
VS版本      Visual Studio 2019

项目下载链接

dll扩展文件

扩展文件下载地址

SQLiteScript文件夹

文件夹下载地址

可视化窗口

可视化窗口下载地址

使用可视化窗口

在这里插入图片描述

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述
在这里插入图片描述

存放到Plugins文件夹

下载好dll扩展文件和SQLiteScript文件夹后,
先把Mono.Data 和Mono.Data.Sqlite 和sqlite3 和 libsqlite3 放到 Assets/Plugins文件夹中
并且把SQLiteScript文件夹也拖拽到Assets当中

如下图
在这里插入图片描述

使用SQLite 数据库(添/删/改/查)

Getdb方法实现 注意:SQLiteHelper填写的数据库路径一定是要在StreamingAssets文件当中 路径不需要写.db文件名后缀
如下图
在这里插入图片描述

    private void Getdb(Action<DbAccess> action)
    {
    
    
        //Path数据库文件,一定是StreamingAssets文件夹下 填写的路径文件不需要填写.db后缀
        //创建数据库读取类
        SQLiteHelper helper = new SQLiteHelper(Path);
        //打开数据库 存储数据库操作类
        using (var db = helper.Open())
        {
    
    
            //调用数据库委托
            action(db);
        }
        /*
         因为每次使用数据 添/删/改/查 都需要使用完后Close掉 
         重复代码,写无数次太麻烦 因为数据库操作类 继承了IDisposable接口 所以,
         using会自动关闭数据库连接,我们无需手动关闭数据库
         */
          
    } 

如果不使用using块套住数据库操作类 需要手动 打开 和关闭数据库

    private void Getdb2(Action<DbAccess> action)
    {
    
    
        //创建数据库读取类
        SQLiteHelper helper = new SQLiteHelper(Path);
        //打开数据库 存储数据库操作类
        var db = helper.Open();
        //调用数据库委托
        action(db);
        //关闭数据库
        db.CloseSqlConnection();

    }

SQLite类型列表

SQLite类型转换表 注意:SQLite类型全都是大写

     SQLite类型 对应  C#数据类型 
     TINYINT          Byte   -->byte
     INT              Int32  -->int
     INTEGER          Int64  -->long
     SINGLE           Single -->float
     DECIMAL          Decimal -->decimal

     BIT              Boolean -->bool  
     BOOLEAN          Boolean -->bool
     注意:bool类型 只能存储 0-1 到数据库中 (0)false (1) true

     DOUBLE           Double -->double (首选)
     REAL             Double -->double 
        
     NVARCHAR         String -->string 
     STRING           String -->string  (首选)
     TEXT             String -->string  文本字符串,存储使用的编码方式为UTF-8UTF-16BE、UTF-16LE
     
     TIME             DateTime
     DATETIME         DateTime (首选)
     生成时间字符串代码:
     DateTime.Now.ToString("s");

数据库存储格式

注意:DataTime 存储数据库的格式:"s"

DateTime.Now.ToString("s");

注意 bool类型存储格式为 0-1

0 代表false  1  代表是true

创建表

需求创建一个表名 为UserInfo
字段名称 UID User Password LoginTime 对应的C#类型 是
long string string DateTime 代码如下

 //创建一个表方法  创建表名UserInfo
 //字段名称 UID    类型为 INTEGER
 // User Password  类型为STRING
 //将LoginTime 类型 设置为DATETIME
 Getdb(db => db.CreateTable("UserInfo", new[] {
    
     "UID", "User", "Password", "LoginTime" },
      new[] {
    
     "INTEGER", "STRING", "STRING", "DATETIME" }));

在这里插入图片描述

插入

需求给对应字段插入数据 分别为 5201314 imdork 142536 当前本地时间 代码如下

//插入字段为 UID / User/ Password / LoginTime
            //对应数据 5201314 imdork 142536   本地时间
                                               //生成时间字符串代码:
                                               //DateTime.Now.ToString("s")
 Getdb(db => db.InsertIntoSpecific("UserInfo", new[] {
    
     "UID", "User", "Password","LoginTime" }
 , new [] {
    
     "5201314", "imdork", "142536", DateTime.Now.ToString("s") }));

在这里插入图片描述

查询

需求查询数据UID 大于50 对应User 字段的数据 和LoginTime 时间对应数据 代码如下:

    //调用Getdb方法
    Getdb(db =>
    {
    
    
        //查询该账号UID 大于50  对应的 LoginTime 和 User 对应字段数据
        var reader = db.SelectWhere("UserInfo", new[] {
    
     "User","LoginTime" },
        new[] {
    
     "UID" }, new[] {
    
     ">" }, new[] {
    
     "50" });

        //调用SQLite工具  解析对应数据
        Dictionary<string, object> pairs = SQLiteTools.GetValue(reader);

        //获取User字段 对应数据
        print("User账号是:" + pairs["User"]);

       //获取账号登录时间
       print("LoginTime登录时间是:" + pairs["LoginTime"]);

   });

最后打印结果
在这里插入图片描述

根据条件查询当行所有字段

        Getdb(obj =>
            {
    
    
                var reader = obj.SelectsWhere("UserInfo",
                    new[] {
    
     "UID", "User" }, new[] {
    
     ">", "=" }, new[] {
    
     "50", "imdork" });

                var keys = SQLiteTools.GetValue(reader);

                foreach (var item in keys)
                {
    
    
                    //打印数据库字段名称  对应字段数值
                    print("数据库字段名为:" + item.Key + "  对应数据值为:" + item.Value);
                }
            }
            );

最后打印
在这里插入图片描述

查询数据库全部数据

在这里插入图片描述
需求:查询表中全部数据 并打印 代码如下:

   //调用Getdb方法
   Getdb(db =>
   {
    
    
         //读取表的全部数据
         var reader = db.ReadFullTable("UserInfo");
         //获取全部数据
         var pairs = SQLiteTools.GetValues(reader);
         //遍历字典数组
         for (int i = 0; i < pairs.Length; i++)
         {
    
    
              //遍历字典
              foreach (var item in pairs[i])
              {
    
    
                   //打印数据库字段名称  对应字段数值
                   print("数据库字段名为:" + item.Key + "  对应数据值为:" + item.Value);
              }
        }
   });

最后控制台输出结果如下:
在这里插入图片描述
注意:使用SQLiteTools类 来解析数据时
解析单行数据 用GetValue方法 ,解析多行数据就要使用 GetValues方法

还有查询bool只能使用以下办法如下方代码

  //查询全部数据
  var reader = db.ReadFullTable("表名");

  //读取下一行数据 第一次调用则 读取数据库第一行数据
  while (SQLiteTools.Read(reader))
  {
    
    
      bool value = SQLiteTools.GetValue(reader, "字段名", i => reader.GetBoolean(i));
  }

更改

在这里插入图片描述
需求查询UID大于50 全部密码更改为123456 代码如下:

//查询该账号UID 大于50数值 的全部符合条件数据  并更改密码为123456
Getdb(db => db.UpdateIntoSpecific("UserInfo", new[] {
    
     "UID" }, new[] {
    
     ">" },
 new[] {
    
     "50" }, new[] {
    
     "Password" }, new[] {
    
     "123456" })); 

代码执行后:如下密码已经成功更改123456
在这里插入图片描述

删除

需求:删除UID 大于50全部数据 代码如下:

//删除UID 大于50全部数据
//                      表名           判断字段        判断符号        具体数据
Getdb(db => db.Delete("UserInfo", new[] {
    
     "UID" }, new[] {
    
     ">" }, new [] {
    
     "50" }));

执行代码后:
在这里插入图片描述

发布注意事项

目前楼主提供资源 只支持 PC端/安卓端
首选点击左上角File - Build Settings -Player Settings
在这里插入图片描述
打开后 找到Player 往下拉找到 Api Compatibility Level* 更改为.Net 4.x 如下图
在这里插入图片描述
设置好后就可以点Build发布项目了
在这里插入图片描述

SQLiteScript文件夹代码展示

SQLite数据操作类(DbAccess)

using UnityEngine;
using System;
using System.Collections;
using Mono.Data.Sqlite;

namespace Imdork.SQLite
{
    
    
	/// <summary>
	/// SQLite数据库操作类
	/// </summary>
	public class DbAccess:IDisposable
	{
    
    
		private SqliteConnection conn; // SQLite连接
		private SqliteCommand cmd; // SQLite命令
		private SqliteDataReader reader;
		public DbAccess(string connectionString)
		{
    
    
			OpenDB(connectionString);
		}
		public DbAccess() {
    
     }

		/// <summary>
		/// 打开数据库
		/// </summary>
		/// <param name="connectionString"></param>
		public void OpenDB(string connectionString)
		{
    
    
			try
			{
    
    
				conn = new SqliteConnection(connectionString);
				conn.Open();
				Debug.Log("Connected to db,连接数据库成功!");
			}
			catch (Exception e)
			{
    
    
				string temp1 = e.ToString();
				Debug.Log(temp1);
			}
		}
		/// <summary>
		/// 关闭数据库连接
		/// </summary>
		public void CloseSqlConnection()
		{
    
    
			if (cmd != null) {
    
     cmd.Dispose(); cmd = null; }
			if (reader != null) {
    
     reader.Dispose(); reader = null; }
			if (conn != null) {
    
     conn.Close(); conn = null; }
			Debug.Log("Disconnected from db.关闭数据库!");
		}

		/// <summary>
		/// 回收资源
		/// </summary>
		public void Dispose()
		{
    
    
			CloseSqlConnection();
		}

		/// <summary>
		/// 执行SQL语句 用于Update/Insert/Delete
		/// </summary>
		/// <param name="sqlQuery"></param>
		/// <returns></returns>
		public int ExecuteNonQuery(string sqlQuery)
        {
    
    
			Debug.Log("ExecuteNonQuery:: " + sqlQuery);
			cmd = conn.CreateCommand();
			cmd.CommandText = sqlQuery;
			int rows = cmd.ExecuteNonQuery();
			return rows;
		}

		

		#region 更新数据
		
		/// <summary>
		/// 更新数据 param tableName=表名  selectkey=查找字段(主键) selectvalue=查找内容 cols=更新字段 colsvalues=更新内容
		/// </summary>
		/// <param name="tableName"></param>
		/// <param name="selectKeys"></param>
		/// <param name="selectValues"></param>
		/// <param name="cols"></param>
		/// <param name="colsValues"></param>
		/// <returns></returns>
		public int UpdateIntoSpecific(string tableName, string[] selectKeys, string[] selectValues, string[] cols, string[] colsValues)
		{
    
    
			string query = "UPDATE " + tableName + " SET " + cols[0] + " = " + "'" + colsValues[0] + "'";

			for (int i = 1; i < colsValues.Length; ++i)
			{
    
    
				query += ", " + cols[i] + " =" + "'" + colsValues[i] + "'";
			}

			query += " WHERE " + selectKeys[0] + " = " + "'" + selectValues[0] + "' ";
			for (int i = 1; i < selectKeys.Length; ++i)
			{
    
    
				query += " AND " + selectKeys[i] + " = " + "'" + selectValues[i] + "' ";
			}
			return ExecuteNonQuery(query);
		}
		/// <summary>
		/// 更新数据 param tableName=表名  selectkey=查找字段(主键) operation=判断的符号 selectvalue=查找内容 cols=更新字段 colsvalues=更新内容
		/// </summary>
		/// <param name="tableName"></param>
		/// <param name="selectKeys"></param>
		/// <param name="operation"></param>
		/// <param name="selectValues"></param>
		/// <param name="cols"></param>
		/// <param name="colsValues"></param>
		/// <returns></returns>
		public int UpdateIntoSpecific(string tableName, string[] selectKeys, string[] operation, string[] selectValues, string[] cols, string[] colsValues)
		{
    
    
			string query = "UPDATE " + tableName + " SET " + cols[0] + " = " + "'" + colsValues[0] + "'";

			for (int i = 1; i < colsValues.Length; ++i)
			{
    
    
				query += ", " + cols[i] + " =" + "'" + colsValues[i] + "'";
			}

			query += " WHERE " + selectKeys[0] + " " + operation[0] + " " + "'" + selectValues[0] + "' ";
			for (int i = 1; i < selectKeys.Length; ++i)
			{
    
    
				query += " AND " + selectKeys[i] + " " + operation[i] + " " + "'" + selectValues[i] + "' ";
			}
			return ExecuteNonQuery(query);
		}
        #endregion

        #region 插入数据	

        #region 插入部分数据
        /// <summary>
        /// 插入部分数据
        /// </summary>
        /// <param name="tableName">表名</param>
        /// <param name="cols">字段名</param>
        /// <param name="values">具体数值</param>
        /// <returns></returns>
        public int InsertIntoSpecific(string tableName, string[] cols, string[] values)
		{
    
    
			if (cols.Length != values.Length)
			{
    
    
				throw new Exception("columns.Length != colType.Length");
			}

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

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

			query += ")";
			return ExecuteNonQuery(query);
		}

        #endregion 

        #region 插入一行数据

        /// <summary>
        /// 插入一行数据 param tableName=表名 values=插入数据内容
        /// </summary>
        public int InsertInto(string tableName, string[] values)
		{
    
    
			string query = "INSERT INTO " + tableName + " VALUES (" + string.Format("'{0}'", values[0]);
			for (int i = 1; i < values.Length; ++i)
			{
    
    
				query += ", " + string.Format("'{0}'",values[i]);
			}
			query += ")";
			return ExecuteNonQuery(query);
		}

        #endregion

        #endregion

        #region 删除表

        #region 根据条件删除表
        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="tableName">表名</param>
        /// <param name="cols">字段</param>
        /// <param name="colsValues">字段值</param>
        /// <returns></returns>
        public int 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 += " and " + cols[i] + " = " + "'" + colsValues[i] + "'";
			}
			return ExecuteNonQuery(query);
		}
		/// <summary>
		/// 删除表
		/// </summary>
		/// <param name="tableName"></param>
		/// <param name="cols"></param>
		/// <param name="operation"></param>
		/// <param name="colsValues"></param>
		/// <returns></returns>
		public int Delete(string tableName, string[] cols,string[] operation, string[] colsValues)
		{
    
    
			string query = "DELETE FROM " + tableName + " WHERE " + cols[0] + " " + operation[0] + " " + "'" + colsValues[0] + "'";

			for (int i = 1; i < colsValues.Length; ++i)
			{
    
    
				query += " and " + cols[i] + " " + operation[i] + " " + "'" + colsValues[i] + "'";
			}
			return ExecuteNonQuery(query);
		}
        #endregion

        /// <summary> 
        /// 删除表中全部数据
        /// </summary>
        public int DeleteContents(string tableName)
		{
    
    
			string query = "DELETE FROM " + tableName;
			return ExecuteNonQuery(query);
		}

		#endregion

		#region 创建表

		/// <summary>
		/// 创建表 param name=表名 col=字段名 colType=字段类型
		/// </summary>
		public int CreateTable(string name, string[] col, string[] colType)
		{
    
    
			if (col.Length != colType.Length)
			{
    
    
				throw new SqliteException("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 ExecuteNonQuery(query);
		}

		#endregion

		#region 查询表

		#region 按条件查询全部数据
		/// <summary>
		/// 按条件查询全部数据 param tableName=表名  col=查找字段 operation=运算符 values=内容
		/// </summary>
		public SqliteDataReader SelectsWhere(string tableName, string[] col, string[] operation, string[] values)
		{
    
    
			if (col.Length != operation.Length || operation.Length != values.Length)
			{
    
    
				throw new SqliteException("col.Length != operation.Length != values.Length");
			}
			string query = "SELECT *";
		
			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);
		}
		/// <summary>
		/// 按条件查询全部数据 param tableName=表名 col=查找字段  values=内容
		/// </summary>
		public SqliteDataReader SelectsWhere(string tableName, string[] col, string[] values)
		{
    
    
			if (col.Length != values.Length)
			{
    
    
				throw new SqliteException("col.Length != values.Length");
			}
			string query = "SELECT *";
			query += " FROM " + tableName + " WHERE " + col[0] + "=" + "'" + values[0] + "' ";
			for (int i = 1; i < col.Length; ++i)
			{
    
    
				query += " AND " + col[i] + "=" + "'" + values[i] + "' ";
			}
			return ExecuteQuery(query);
		}
		#endregion

		#region 按条件查询数据
		/// <summary>
		/// 按条件查询数据 param tableName=表名 items=查询字段 col=查找字段 operation=运算符 values=内容
		/// </summary>
		public SqliteDataReader SelectWhere(string tableName, string[] items, string[] col, string[] operation, string[] values)
		{
    
    
			if (col.Length != operation.Length || operation.Length != values.Length)
			{
    
    
				throw new SqliteException("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);
		}
		/// <summary>
		/// 按条件查询数据 param tableName=表名 items=查询字段 col=查找字段  values=内容
		/// </summary>
		public SqliteDataReader SelectWhere(string tableName, string[] items, string[] col, string[] values)
		{
    
    
			if (col.Length != values.Length)
			{
    
    
				throw new SqliteException("col.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] + "=" + "'" + values[0] + "' ";
			for (int i = 1; i < col.Length; ++i)
			{
    
    
				query += " AND " + col[i] + "=" + "'" + values[i] + "' ";
			}
			return ExecuteQuery(query);
		}
		#endregion

		#region 按条件查询 单个字段数据

		/// <summary>
		/// 查询表
		/// </summary>
		public SqliteDataReader Select(string tableName, string col, string operation, string values)
		{
    
    
			string query = "SELECT * FROM " + tableName + " WHERE " + col + " " + operation + " " + string.Format("'{0}'", values);
			return ExecuteQuery(query);
		}
		/// <summary>
		/// 查询表
		/// </summary>
		public SqliteDataReader Select(string tableName, string col, string values)
		{
    
    
			string query = "SELECT * FROM " + tableName + " WHERE " + col + " = " + string.Format("'{0}'", values);
			return ExecuteQuery(query);
		}
		#endregion

		#region  升序查询/降序查询/查询表行数/查询表全部数据
		/// <summary>
		/// 升序查询
		/// </summary>
		public SqliteDataReader SelectOrderASC(string tableName, string col)
		{
    
    
			string query = "SELECT * FROM " + tableName + " ORDER BY " + col + " ASC";
			return ExecuteQuery(query);
		}
		/// <summary>
		/// 降序查询
		/// </summary>
		public SqliteDataReader SelectOrderDESC(string tableName, string col)
		{
    
    
			string query = "SELECT * FROM " + tableName + " ORDER BY " + col + " DESC";
			return ExecuteQuery(query);
		}
		/// <summary>
		/// 查询表行数
		/// </summary>
		public SqliteDataReader SelectCount(string tableName)
		{
    
    
			string query = "SELECT COUNT(*) FROM " + tableName;
			return ExecuteQuery(query);
		}
		/// <summary>
		/// 查询表中全部数据 param tableName=表名 
		/// </summary>
		public SqliteDataReader ReadFullTable(string tableName)
		{
    
    
			string query = "SELECT * FROM " + tableName;
			return ExecuteQuery(query);
		}
		#endregion

		/// <summary>
		/// 执行SQL语句 用于SelectWhere查询语句
		/// </summary>
		/// <param name="sqlQuery"></param>
		/// <returns></returns>
		public SqliteDataReader ExecuteQuery(string sqlQuery)
		{
    
    
			Debug.Log("ExecuteQuery:: " + sqlQuery);
			cmd = conn.CreateCommand();
			cmd.CommandText = sqlQuery;
			reader = cmd.ExecuteReader();
			return reader;
		}
		 
		#endregion

		
	}
}

SQLite访问类(SQLiteHelper)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using UnityEngine.Networking;

namespace Imdork.SQLite
{
    
    
    /// <summary>
    /// SQLite访问类
    /// </summary>
    public class SQLiteHelper
    {
    
    
        /// <summary>
        /// 填写StreamingAssets中数据库路径文件
        /// </summary>
        /// <param name="path">数据库路径</param>
        public SQLiteHelper(string path)
        {
    
    
            //调用更新路径方法
            UpdatePath(path);
        }
        /// <summary>
        /// 更新路径的方法
        /// </summary>
        /// <param name="path"></param>
        public void UpdatePath(string path)
        {
    
    
            //给路径添加.db后缀 并赋值给数据库路径
            datebasePath = string.Format("{0}.db", path);
            //获取路径名称 加后缀db 并赋值给数据库名称
            datebaseName = Path.GetFileName(datebasePath);
        }

        /// <summary>
        /// 数据库名称
        /// </summary>
        string datebaseName;

        /// <summary>
        /// 数据库路径
        /// </summary>
        string datebasePath;
     
        /// <summary>
        /// 打开数据库
        /// </summary>
        public DbAccess Open()
        {
    
    
            string url = "URI = file:" + appDBPath();
            var db = new DbAccess();
            db.OpenDB(url);
            return db;
        }
     
          
        /// <summary>
        /// 根据平台读取对应StreamingAssets路径
        /// </summary>
        /// <returns></returns>
        private string appDBPath()
        {
    
    

            string path;

#if UNITY_EDITOR
            path = Application.streamingAssetsPath + "/" + datebasePath;
#elif UNITY_ANDROID

            // 沙盘路径
            path = Application.persistentDataPath + "/" + datebaseName;

            //如果查找该文件路径
            if (File.Exists(path))
            {
    
    
                //返回该数据库路径
                return path;
            }

            // jar:file:是安卓手机路径的意思  
            // Application.dataPath + "!/assets/"   即  Application.dataPath/StreamingAssets  
            var request = UnityWebRequest.Get("jar:file://" + Application.dataPath + "!/assets/" + datebasePath);
            request.SendWebRequest(); //读取数据
            while (!request.downloadHandler.isDone) {
    
     }
            // 因为安卓中streamingAssetsPath路径下的文件权限是只读,所以获取之后把他拷贝到沙盘路径中
            File.WriteAllBytes(path, request.downloadHandler.data);
#else
       path = Application.streamingAssetsPath + "/" + datebasePath;
#endif



            return path;
        }

        /// <summary>
        /// 删除数据库 整个db文件删除掉
        /// </summary>
        public void Delete()
        {
    
    
            //删除文件方法
            File.Delete(appDBPath());
        }

        /// <summary>
        /// 查询db文件是否存在
        /// </summary>
        /// <returns></returns>
        public bool Find()
        {
    
    
            //查询文件的方法
            return File.Exists(appDBPath());
        }
         
    }
}

SQLite 解析数据工具类 (SQLiteTools)

using System.Collections;
using System.Collections.Generic;
using Mono.Data.Sqlite;
using System;

namespace Imdork.SQLite
{
    
    
    /*
     SqliteDataReader 类使用方法:
     
     bool Read()方法 查看查询出来数据 有没有可读字段,如果有返回 true 否则反之 false

     int GetOrdinal(string Name)方法  传递数据库字段名 返回对应序列号
 
     bool IsDBNull(int i)方法  接收字段名称序列号 判断该序列号是否为空 是空为true 反之为false

     object GetValue(int i)方法  接收字段名称序列号 返回对应字段数据

     FieldCount属性 获取该行字段数量

     string GetName(int i)方法 参数传递行索引 返回对应字段名称
     
     */
    /*
     SQLite类型 对应  C#数据类型   
     TINYINT          Byte   -->byte
     INT              Int32  -->int
     INTEGER          Int64  -->long
     SINGLE           Single -->float
     DECIMAL          Decimal -->decimal

     BIT              Boolean -->bool  
     BOOLEAN          Boolean -->bool
     注意:bool类型 只能存储 0-1 到数据库中 (0)false (1) true

     DOUBLE           Double -->double (首选)
     REAL             Double -->double 
        
     NVARCHAR         String -->string 
     STRING           String -->string  (首选)
     TEXT             String -->string  文本字符串,存储使用的编码方式为UTF-8、UTF-16BE、UTF-16LE
     
     TIME             DateTime
     DATETIME         DateTime (首选)
     生成时间字符串代码:
     DateTime.Now.ToString("s");
     
     */
    /*
     SQLite 数据类型	C# 数据类型	 
     BIGINT	             Int64	 
     BIGUINT	         UInt64	 
     BINARY	             Binary	 
     BIT	             Boolean	            首选
     BLOB	             Binary	                首选
     BOOL	             Boolean	 
     BOOLEAN	         Boolean	 
     CHAR	             AnsiStringFixedLength	首选
     CLOB	             String	 
     COUNTER	         Int64	 
     CURRENCY	         Decimal	 
     DATE	             DateTime	 
     DATETIME	         DateTime	            首选
     DECIMAL	         Decimal	            首选
     DOUBLE	             Double	 
     FLOAT	             Double	 
     GENERAL	         Binary	 
     GUID	             Guid	 
     IDENTITY	         Int64	 
     IMAGE	             Binary	 
     INT	             Int32	                首选
     INT8	             SByte	 
     INT16	             Int16	 
     INT32	             Int32	 
     INT64	             Int64	 
     INTEGER	         Int64	                首选
     INTEGER8	         SByte	 
     INTEGER16	         Int16	 
     INTEGER32	         Int32	 
     INTEGER64	         Int64	 
     LOGICAL	         Boolean	 
     LONG	             Int64	 
     LONGCHAR	         String	 
     LONGTEXT	         String	 
     LONGVARCHAR	     String	 
     MEMO	             String	 
     MONEY	             Decimal	 
     NCHAR	             StringFixedLength	    首选
     NOTE	             String	 
     NTEXT	             String	 
     NUMBER	             Decimal	 
     NUMERIC	         Decimal	 
     NVARCHAR	         String	                首选
     OLEOBJECT	         Binary	 
     RAW	             Binary	 
     REAL	             Double	                首选
     SINGLE	             Single	                首选
     SMALLDATE	         DateTime	 
     SMALLINT	         Int16	                首选
     SMALLUINT	         UInt16	                首选
     STRING	             String	 
     TEXT	             String	 
     TIME	             DateTime	 
     TIMESTAMP	         DateTime	 
     TINYINT	         Byte	                首选
     TINYSINT	         SByte	                首选
     UINT	             UInt32	                首选
     UINT8	             Byte	 
     UINT16	             UInt16	 
     UINT32	             UInt32	 
     UINT64	             UInt64	 
     ULONG	             UInt64	 
     UNIQUEIDENTIFIER	 Guid	                首选
     UNSIGNEDINTEGER	 UInt64	                首选
     UNSIGNEDINTEGER8	 Byte	 
     UNSIGNEDINTEGER16	 UInt16	 
     UNSIGNEDINTEGER32	 UInt32	 
     UNSIGNEDINTEGER64	 UInt64	 
     VARBINARY	         Binary	 
     VARCHAR	         AnsiString	            首选
     VARCHAR2	         AnsiString	 
     YESNO	             Boolean
     */
    /// <summary>
    /// SQLite 解析数据工具类
    /// </summary>
    public class SQLiteTools
    {
    
    
        /// <summary>
        /// 获取单行数据库 字段名称 对应数据对象 方法内会调用Read()
        /// </summary>
        /// <param name="reader">数据库读取器</param>
        /// <returns></returns>
        public static Dictionary<string, object> GetValue(SqliteDataReader reader)
        {
    
    
            if (!reader.Read())
            {
    
    
                return null;
            }
            return ReadValue(reader);
        }

        /// <summary>
        /// 获取多行数据库 字段名称 对应数据对象   方法内会调用Read()
        /// </summary>
        /// <param name="reader">数据库读取器</param>
        /// <returns></returns>
        public static Dictionary<string, object>[] GetValues(SqliteDataReader reader)
        {
    
    
            if (!reader.Read())
            {
    
    
                return null;
            }

            var Line = new List<Dictionary<string, object>>();
            do
            {
    
    
                Line.Add(ReadValue(reader));

            } while (reader.Read());

            return Line.ToArray();
        }
     
        /// <summary>
        /// 读取该行数据方法
        /// </summary>
        /// <param name="reader"></param>
        /// <returns></returns>
        private static Dictionary<string, object> ReadValue(SqliteDataReader reader)
        {
    
    
            //初始化字典的方法
            var Line = new Dictionary<string, object>();

            //遍历当前行中列数
            for (int i = 0; i < reader.FieldCount; i++)
            {
    
    
                //获取该字段名称
                string colName = reader.GetName(i);

                //判断该字段数据是否为null
                if(IsDBNull(reader,colName))
                {
    
    
                    //暂停循环
                    continue;
                }

                //获取数据的方法
                object value = GetValue(reader, colName);

                //存储到字典中
                Line.Add(colName, value);
            }

            //返回字典
            return Line;
        }

        /// <summary>
        /// 判断该字段是否为空  需要手动调用Read()方法
        /// </summary>
        /// <param name="reader">数据库读取器</param>
        /// <param name="colName">字段名称</param>
        /// <returns></returns>
        public static bool IsDBNull(SqliteDataReader reader, string colName)
        {
    
    
            int colOrdinal = reader.GetOrdinal(colName);
            return reader.IsDBNull(colOrdinal);
        }

        /// <summary>
        /// 获取数据的方法  需要手动调用Read()方法
        /// </summary>
        /// <param name="reader">数据库读取器</param>
        /// <param name="colName">字段名称</param>
        /// <returns></returns>
        public static object GetValue(SqliteDataReader reader, string colName)
        {
    
    
            int colOrdinal = reader.GetOrdinal(colName);
            return reader.GetValue(colOrdinal);
        }

        /// <summary>
        /// 获取数据的方法  自定义类型获取 需要手动调用Read()
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="reader">数据读取类</param>
        /// <param name="colName">字段名称</param>
        /// <param name="action">获取对应类型数据</param>
        /// <returns></returns>
        public static T GetValue<T>(SqliteDataReader reader,string colName,Func<int,T> action)
        {
    
    
            int colOrdinal = reader.GetOrdinal(colName);
            return action(colOrdinal);
        }

        /// <summary>
        /// 读取的方法 需要读取下一行数据时调用 (如果是第一次读取数据 还是读取第一行数据)
        /// </summary>
        /// <param name="reader">数据库读取类</param>
        /// <returns></returns>
        public static bool Read(SqliteDataReader reader)
        {
    
    
            return reader.Read();
        }
         
    }
     
}

猜你喜欢

转载自blog.csdn.net/qq_43333567/article/details/125687424