浅谈Unity之读取Excel表格保存到Sqlite数据库

本文涉及的产品
模型在线服务 PAI-EAS,A10/V100等 500元 1个月
模型训练 PAI-DLC,5000CU*H 3个月
交互式建模 PAI-DSW,5000CU*H 3个月
简介: 读取Excel表格保存到Sqlite数据库

1.读取Excel表格和保存sqlite数据库所用到的dll文件  

最后如下图所示


废话不多说了,直接上代码吧


using System.Collections;

using System.Collections.Generic;

using UnityEngine;

using Mono.Data.Sqlite;

using System;

using System.IO;

using System.Data;

using Excel;

public class SQLiteDataBase

{

   private SqliteConnection conn; // SQLite连接

   private SqliteDataReader reader;

   private SqliteCommand command;// SQLite命令

   private float timespeed = 0.001f;

   /// <summary>

   /// 执行SQL语句  公共方法

   /// </summary>

   /// <param name="sqlQuery"></param>

   /// <returns></returns>

   public SqliteDataReader ExecuteQuery(string sqlQuery)

   {

       command = conn.CreateCommand();

       command.CommandText = sqlQuery;

       reader = command.ExecuteReader();

       return reader;

   }

   #region 打开/关闭数据库

   /// <summary>

   /// 打开数据库

   /// </summary>

   /// <param name="connectionString">@"Data Source = " + path</param>

   public SQLiteDataBase(string connectionString)

   {

       try

       {

           //构造数据库连接

           conn = new SqliteConnection(connectionString);

           //打开数据库

           conn.Open();

           Debug.Log("打开数据库");

       }

       catch (Exception e)

       {

           Debug.Log(e.Message);

       }

   }

   /// <summary>

   /// 关闭数据库连接

   /// </summary>

   public void CloseSqlConnection()

   {

       if (command != null) { command.Dispose(); command = null; }

       if (reader != null) { reader.Dispose(); reader = null; }

       if (conn != null) { conn.Close(); conn = null; }

       Debug.Log("关闭数据库!");

   }

   #endregion;

   #region 创建表单

   /// <summary>

   /// 创建表单  第一种

   /// </summary>

   /// <param name="name">表单名</param>

   /// <param name="col">字段</param>

   /// <param name="colType">类型</param>

   public void CreationMenu(string name, string[] col, string[] colType)

   {

       string query = "create table " + name + " (" + col[0] + " " + colType[0];

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

       {

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

       }

       query += ")";        

       command = new SqliteCommand(query, conn);

       command.ExecuteNonQuery();

   }

   /// <summary>  第二种  区别第一种用了公共方法  原理应该是一样的  经测试都可以使用

   /// 创建表  param name=表名 col=字段名 colType=字段类型

   /// </summary>

   public SqliteDataReader 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 ExecuteQuery(query);

   }

   #endregion;

   #region 查询数据

   /// <summary>

   /// 查询表中全部数据 param tableName=表名  

   /// </summary>

   public SqliteDataReader ReadFullTable(string tableName)

   {

       string query = "SELECT * FROM " + tableName;

       return ExecuteQuery(query);

   }

   /// <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>

   /// 查询表

   /// </summary>

   public SqliteDataReader Select(string tableName, string col, string values)

   {

       string query = "SELECT * FROM " + tableName + " WHERE " + col + " = " + values;

       return ExecuteQuery(query);

   }

   public SqliteDataReader Select(string tableName, string col, string operation, string values)

   {

       string query = "SELECT * FROM " + tableName + " WHERE " + col + operation + values;

       return ExecuteQuery(query);

   }

   /// <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);

   }

   #endregion

   #region 插入数据

   /// <summary>

   /// 插入数据 param tableName=表名 values=插入数据内容

   /// 插入一条数据

   /// </summary>

   public SqliteDataReader 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 += "')";

       return ExecuteQuery(query);

   }

   /// <summary>

   /// 插入数据     插入多条数据

   /// </summary>    经测试这个方法是可用的

   /// 因为我的数据有两万条运行卡着不动了,所以用协程时间控制一下 虽然慢但是不卡死,写到数据库中之后用数据库就好了

   /// <param name="tableName">表名字</param>

   /// <param name="values">字典</param>

   /// <returns></returns>

   public IEnumerator InsertInto(string tableName, Dictionary<string, List<string>> values)

   {

       int ii = 0;

       foreach (var item in values)

       {

           string query = "";

           string value = "";

           foreach (var ite in item.Value)

           {

               value += "','" + ite;

           }

           query = "INSERT INTO " + tableName + " VALUES ('" + item.Key + value + "')";

           //Debug.Log(query);

           command = conn.CreateCommand();

           command.CommandText = query;

           command.ExecuteNonQuery();

           Debug.Log("写入成功" + ii++);

           yield return new WaitForSeconds(timespeed);

       }

       Debug.Log("写入成功");

   }

 

   #region 没测试过的

   /// <summary>

   /// 插入数据 param tableName=表名 cols=插入字段 value=插入内容

   /// </summary>

   public SqliteDataReader InsertIntoSpecific(string tableName, string[] cols, string[] values)

   {

       if (cols.Length != values.Length)

       {

           throw new SqliteException("columns.Length != values.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 ExecuteQuery(query);

   }

   /// <summary>

   /// 更新数据 param tableName=表名 cols=更新字段 colsvalues=更新内容 selectkey=查找字段(主键) selectvalue=查找内容

   /// </summary>

   public SqliteDataReader 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);

   }

   #endregion

   #endregion

   #region 删除

   /// <summary>

   /// 删除表   IF EXISTS判断表存不存在防止出错  已测试

   /// </summary>

   public SqliteDataReader DeleteContents(string tableName)

   {

       string query = "DROP TABLE IF EXISTS " + tableName;

       Debug.Log("删除表成功");

       return ExecuteQuery(query);

   }

   /// <summary>

   /// 删除数据 param tableName=表名 cols=字段 colsvalues=内容  

   /// </summary>

   public SqliteDataReader 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];

       }

       return ExecuteQuery(query);

   }

   #endregion

}

public class SQLiteDataBaseTion : MonoBehaviour

{

   [Header("Excel表数据长度")]   //表格一共有多少列数 最长的一个

   public int tableint;

   public string[] fields, type;   //字段\类型

   [Header("数据库名字")]

   public string dbname;

   private SQLiteDataBase _SQLiteData;

   private SqliteDataReader reader;

   private string path;

   private  string connectionString;

   public static Dictionary<string, List<string>> JDDateDic = new Dictionary<string, List<string>>();//机电数据

   public static Dictionary<string, List<string>> OneCDateDic = new Dictionary<string, List<string>>();//一层数据

   private void Awake()

   {

       fields = new string[tableint];

       type = new string[tableint];

       for (int i = 0; i < tableint; i++)

       {

           fields[i] = "sql" + i.ToString();

           type[i] = "varchar";

       }

   }

   // Start is called before the first frame update

   void Start()

   {

       //读取excel表格数据

       ReadExcelClick("jiegou.xlsx", 0, OneCDateDic);

       path = Application.streamingAssetsPath + "/"+ dbname + ".db";

       connectionString = @"Data Source = " + path;

       //创建数据库文件  存在就打开

       CreateSQL(dbname);        

       //创建表

       //_SQLiteData.CreationMenu("jiegou", fields, type);

       //将数据插入数据库

       //StartCoroutine(_SQLiteData.InsertInto("jiegou", OneCDateDic));

       //删除表  

       //_SQLiteData.DeleteContents("jiegou");

   }

   /// <summary>

   ///   创建数据库文件

   /// </summary>

   /// <param name="sqlname">文件名字</param>

   public void CreateSQL(string sqlname)

   {

       if (!File.Exists(Application.streamingAssetsPath + "/" + sqlname + ".db"))

       {

           //不存在就创建

           File.Create(Application.streamingAssetsPath + "/" + sqlname + ".db");

           //创建之后再打开

           _SQLiteData = new SQLiteDataBase(connectionString);

       }

       else

       {

           Debug.Log("已存在");

           //打开数据库

           _SQLiteData = new SQLiteDataBase(connectionString);

       }

   }

   /// 读取数据库某一行数据    "646c173c-7d14-47b0-80fe-53c1c8ce2b0e-0037044a"

   public List<string> SomeLine(string idname,out List <string >listidnames)

   {

       reader = _SQLiteData.ReadFullTable("jidian");

       List<string> idname_ = new List<string>();

       while (reader.Read())

       {

           //Debug.Log(reader.GetString(reader.GetOrdinal("idname")));//  reader.ToString();

           if (reader.GetString(0).ToString() == idname)

           {

               for (int i = 0; i < reader.FieldCount; i++)

               {

                   try

                   {

                       if (reader.GetString(i) != null)

                       {

                           Debug.Log(reader.GetString(i));

                           idname_.Add(reader.GetString(i));

                       }

                   }

                   catch (Exception e)

                   {

                       Debug.Log(e.Message);

                       break;

                   }

               }

               listidnames = idname_;

               return listidnames;

           }          

       }

       listidnames = idname_;

       return listidnames;

   }

   //读取 Excel表格

   void ReadExcelClick(string _name, int _num, Dictionary<string, List<string>> _Dic)

   {

       //1.打开文件,创建一个文件流操作对象

       //FileStream fileStream = new FileStream(Application.streamingAssetsPath + "/" + "机电.xlsx", FileMode.Open, FileAccess.Read);

       FileStream fileStream = new FileStream(Application.streamingAssetsPath + "/" + _name, FileMode.Open, FileAccess.Read);

       //2.创建一个excel读取类

       IExcelDataReader reader = ExcelReaderFactory.CreateOpenXmlReader(fileStream);

       //方法1:读取

       //while (reader.Read())

       //{

       //    string name = reader.GetString(0);

       //    string birth = reader.GetString(1);

       //    string brief = reader.GetString(2);

       //    Debug.Log("姓名:" + name + " --- " + "生卒:" + birth + " --- " + "简介:" + brief);

       //}

       //方法2:读取

       DataSet result = reader.AsDataSet();

       //获取行数

       int rows = result.Tables[_num].Rows.Count;

       Debug.Log(rows);

       //获取列数

       int column = result.Tables[_num].Columns.Count;

       for (int i = 0; i < rows; i++)

       {

           //获取i行的第一列数据

           string name = result.Tables[_num].Rows[i][0].ToString();

           List<string> _S = new List<string>();

           for (int j = 1; j < column; j++)

           {

               string birth = result.Tables[_num].Rows[i][j].ToString();

               _S.Add(birth);

           }

           if (_Dic.ContainsKey(name))

           {

               continue;

           }

           _Dic.Add(name, _S);

       }

       Debug.Log(_Dic.Count);

   }

   private void OnDisable()

   {

       _SQLiteData.CloseSqlConnection();

   }

   // Update is called once per frame

   void Update()

   {

     

   }

}


相关文章
|
4天前
|
存储 API 数据库
QML使用Sqlite数据库存储ListModel数据
本文介绍了在QML中使用Sqlite数据库存储ListModel数据的方法,包括如何创建数据库、读取数据、动态添加和删除数据,以及如何在程序启动和退出时与数据库同步数据。
|
4天前
|
数据库 数据库管理
qt对sqlite数据库多线程的操作
本文总结了在Qt中进行SQLite数据库多线程操作时应注意的四个关键问题,包括数据库驱动加载、加锁、数据库的打开与关闭,以及QsqlQuery变量的使用。
|
2月前
|
人工智能 小程序 Java
【工具】轻松解锁SQLite数据库,一窥微信聊天记录小秘密
本文介绍了一款名为PyWxDump的开源工具,它可以获取微信账户信息、解密SQLite数据库以查看和备份聊天记录。此工具适用于已登录电脑版微信的用户,通过GitHub下载后简单几步即可操作。适合对数据恢复感兴趣的开发者,但请注意合法合规使用并尊重隐私。
200 2
【工具】轻松解锁SQLite数据库,一窥微信聊天记录小秘密
|
6天前
|
SQL 数据库 数据库管理
SQLite 创建数据库
SQLite 的 sqlite3 命令被用来创建新的 SQLite 数据库。您不需要任何特殊的权限即可创建一个数据。
13 0
|
8天前
|
JSON NoSQL 数据库
和SQLite数据库对应的NoSQL数据库:TinyDB的详细使用(python3经典编程案例)
该文章详细介绍了TinyDB这一轻量级NoSQL数据库的使用方法,包括如何在Python3环境中安装、创建数据库、插入数据、查询、更新以及删除记录等操作,并提供了多个编程案例。
19 0
|
2月前
|
SQL 存储 小程序
【教程】navicat配合HTTP通道远程连接SQLite数据库
本文介绍了如何通过 Navicat Premium 工具配合 n_tunnel_sqlite.php 和 HTTP 通道远程连接服务器上的 SQLite 数据库。SQLite 是一种自给自足的、无服务器的 SQL 数据库引擎,由于其端口未对外开放,直接使用 Navicat 进行远程连接不可行。文章详细记录了使用 HTTP 通道实现远程连接的过程,包括定位本地 `ntunnel_sqlite.php` 文件,将其上传至服务器,并通过 Navicat 配置 HTTP 通道连接 SQLite 数据库的具体步骤。
50 0
【教程】navicat配合HTTP通道远程连接SQLite数据库
|
2月前
|
Java 数据库连接 数据库
java系列之~如何给sqlite数据库添加表
这篇文章介绍了如何在Java中使用SQLite JDBC驱动来连接SQLite数据库,并提供了示例代码来演示如何创建一个新的数据库表。
|
2月前
|
SQL 存储 数据库
SQLite数据库
【8月更文挑战第21天】SQLite数据库
36 3
|
2月前
|
存储 数据库 数据库管理
SQLite数据库的备份
【8月更文挑战第20天】SQLite数据库的备份
119 1
|
2月前
|
人工智能 BI
用ChatGPT做excel表格真香!只需动嘴提要求和复制粘贴
用ChatGPT做excel表格真香!只需动嘴提要求和复制粘贴
下一篇
无影云桌面