unity读取Excel表格保存到Sqlite数据库
1.读取Excel表格和保存sqlite数据库所用到的dll文件 下载链接: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()
{ }
}
c#脚本亲测可用

搜索
复制
unity读取Excel表格保存到Sqlite数据库的更多相关文章
- 快速将excel数据保存到Oracle数据库中【转】
我们在工作中,也许会碰到以下情况,客户或者同事发来需要调查的数据,并不是dmp文件,而是excel文件,此时通常是一张表,少量几条记录.最近我恰好碰到了这种情况,所以做了些调查,不敢藏私,拿出来跟大家 ...
- Android把图片保存到SQLite中
1.bitmap保存到SQLite 中 数据格式:Blob db.execSQL("Create table " + TABLE_NAME + "( _id INTEGE ...
- php将图片以二进制保存到mysql数据库并显示
一.存储图片的数据表结构: -- -- 表的结构 `image` -- CREATE TABLE IF NOT EXISTS `image` ( `id` int(3) NOT NULL AUTO_I ...
- 读取Excel表格中数据原型
写下这篇博客来记录自己的工作,这部分功能是读取Excel表格中的数据,并通过c#中的datagridview控件将读取的数据显示出来.为了方便用户,我设计了一个read按钮,用户点击这个按钮,会弹出打 ...
- C# 读取Excel表格内容,以及NPOI的使用
在实际的开发中,我们可能需要读写word或者Excel的内容,在我开发的项目中,需要读取Excel的内容,并将相对应的内容存储到数据库中,这里简单跟大家分享一下,希望能够帮助一些人. 我相信在读写wo ...
- node 爬虫 --- 将爬取到的数据,保存到 mysql 数据库中
步骤一:安装必要模块 (1)cheerio模块 ,一个类似jQuery的选择器模块,分析HTML利器. (2)request模块,让http请求变的更加简单 (3)mysql模块,node连接mysq ...
- 爬虫双色球所有的历史数据并保存到SQLite
前言 上一篇介绍了双色球走势图是怎么实现的,这一篇介绍怎么实现爬虫所有的双色球历史数据,也可以同步分享怎么同步福彩3D数据.采用的C#来实现的. 同步双色球的地址:https://datachart. ...
- android如何保存读取读取文件文件保存到SDcard
android如何保存读取读取文件文件保存到SDcard 本文来源于www.ifyao.com禁止转载!www.ifyao.com 上图为保存文件的方法体. 上图为如何调用方法体保存数据. 上面的截图 ...
- Java读取excel表格
Java读取excel表格 一般都是用poi技术去读取excel表格的,但是这个技术又是什么呢 什么是Apache POI? Apache POI是一种流行的API,它允许程序员使用Java程序创建, ...
- C#读取Excel表格中数据并返回datatable
在软件开发的过程中,经常用到从excel表格中读取数据作为数据源,以下整理了一个有效的读取excel表格的方法. DataTable GetDataTable(string tableName,str ...
随机推荐
- WPF-序列化
public class SerializeHelper { #region 二进制格式 /// <summary> /// Binary 序列化使用前需要标记类可序列化 /// < ...
- keil调试教程
点击跳转 如果开启调试就提示弹框错误2k,说明你没有破解你的keil,网上自行下载注册机. 调试一定要对应自己板子的晶振,否则当你测试你的延时实际时间时,keil里的sec会不一样,甚至离谱.
- Flink1.11 解决 No ExecutorFactory found to execute the application
在使用Flink1.11的时候写了个本地Test 运行的时候发现报错了,具体如下 Exception in thread "main" java.lang.IllegalState ...
- java spring 理解
1.spring IOC容器 其实就是 new 了一个 ApplicationContext 类对象.->应用上下文对象. 2.应用上下文对象 实例化.配置,并管理 bean. 所以上下文对象是 ...
- OS-lab5
OS-lab5 磁盘管理 完成文件系统的第一步就是要能够处理磁盘等外设的信息. lib/syscall_all.c 处理磁盘的信息,最基本的就是对磁盘进行读写操作. sys_write_dev函数用于 ...
- js match方法
1.用法 match()方法可以字符串中检索指定的值,或者是匹配一个或多个正则表达式 2.返回值 该方法类似于indexOf()/lastIndexOf(),区别就是返回值不一样 indexOf()/ ...
- 给含有关键词的label着色
给含有关键词的label着色 FineFileType() { let arr = document.querySelectorAll('.el-checkbox__label'); for (let ...
- MQTT QoS 0, 1, 2 介绍
什么是 QoS 很多时候,使用 MQTT 协议的设备都运行在网络受限的环境下,而只依靠底层的 TCP 传输协议,并不能完全保证消息的可靠到达.因此,MQTT 提供了 QoS 机制,其核心是设计了多种消 ...
- c++游戏编程(2)多文件编程与命名空间
文章目录 前言 1 多文件编程 1.1 头文件 1.1.1 头文件的组成 1.1.2 头文件的储存 1.2 多文件编程 2 命名空间 总结 引用文章 前言 这是我的第二篇博客 上篇文章写了很多c++开 ...
- eNSP报错41解决方法
1.点击右上角的菜单 2.工具>>注册设备,全部勾选,然后注册,就行了.