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数据库的更多相关文章

  1. 快速将excel数据保存到Oracle数据库中【转】

    我们在工作中,也许会碰到以下情况,客户或者同事发来需要调查的数据,并不是dmp文件,而是excel文件,此时通常是一张表,少量几条记录.最近我恰好碰到了这种情况,所以做了些调查,不敢藏私,拿出来跟大家 ...

  2. Android把图片保存到SQLite中

    1.bitmap保存到SQLite 中 数据格式:Blob db.execSQL("Create table " + TABLE_NAME + "( _id INTEGE ...

  3. php将图片以二进制保存到mysql数据库并显示

    一.存储图片的数据表结构: -- -- 表的结构 `image` -- CREATE TABLE IF NOT EXISTS `image` ( `id` int(3) NOT NULL AUTO_I ...

  4. 读取Excel表格中数据原型

    写下这篇博客来记录自己的工作,这部分功能是读取Excel表格中的数据,并通过c#中的datagridview控件将读取的数据显示出来.为了方便用户,我设计了一个read按钮,用户点击这个按钮,会弹出打 ...

  5. C# 读取Excel表格内容,以及NPOI的使用

    在实际的开发中,我们可能需要读写word或者Excel的内容,在我开发的项目中,需要读取Excel的内容,并将相对应的内容存储到数据库中,这里简单跟大家分享一下,希望能够帮助一些人. 我相信在读写wo ...

  6. node 爬虫 --- 将爬取到的数据,保存到 mysql 数据库中

    步骤一:安装必要模块 (1)cheerio模块 ,一个类似jQuery的选择器模块,分析HTML利器. (2)request模块,让http请求变的更加简单 (3)mysql模块,node连接mysq ...

  7. 爬虫双色球所有的历史数据并保存到SQLite

    前言 上一篇介绍了双色球走势图是怎么实现的,这一篇介绍怎么实现爬虫所有的双色球历史数据,也可以同步分享怎么同步福彩3D数据.采用的C#来实现的. 同步双色球的地址:https://datachart. ...

  8. android如何保存读取读取文件文件保存到SDcard

    android如何保存读取读取文件文件保存到SDcard 本文来源于www.ifyao.com禁止转载!www.ifyao.com 上图为保存文件的方法体. 上图为如何调用方法体保存数据. 上面的截图 ...

  9. Java读取excel表格

    Java读取excel表格 一般都是用poi技术去读取excel表格的,但是这个技术又是什么呢 什么是Apache POI? Apache POI是一种流行的API,它允许程序员使用Java程序创建, ...

  10. C#读取Excel表格中数据并返回datatable

    在软件开发的过程中,经常用到从excel表格中读取数据作为数据源,以下整理了一个有效的读取excel表格的方法. DataTable GetDataTable(string tableName,str ...

随机推荐

  1. Sql Sugar 使用

    sql sugar orm文档地址: SqlSugar ORM 5.X 官网 .文档.教程 - SqlSugar 5x - .NET果糖网 (donet5.com) sql sugar 基本用法大全, ...

  2. RestTemplate 设置超时时间

    不废话直接上代码 SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); reque ...

  3. Vue-cli JSX踩坑问题!

    今天封装一个公用组件库,期间使用到了JSX,发现在Data配置中去配置渲染函数出现了 h function is not defined的问题?? 网上查询一大堆所谓安装JSX的东西,其实Vue-cl ...

  4. HJ92 在字符串中找出连续最长的数字串

    描述 输入一个字符串,返回其最长的数字子串,以及其长度.若有多个最长的数字子串,则将它们全部输出(按原字符串的相对位置) 本题含有多组样例输入. 输入描述: 输入一个字符串. 输出描述: 输出字符串中 ...

  5. win10系统每次重启桌面图标排列都会改动怎么办

    鼠标右键点击个性化>主题>找到桌面图标设置>把计算机 回收站 用户的文件 控制面板 网络等前面框复选框全部勾选掉,然后在桌面新建文件夹把桌面所有的图标剪切到新建文件里面,然后把新建文 ...

  6. Flink任务自定义个性化配置logback.xml文件

    之前已经写过如何使用logback将日志直接写入Kafka,然后通过es和kibana实时查看 但是如果我们想要每个任务都能够带上单独的信息比如开发者.任务名称等信息,那么就需要每个任务都指定一个lo ...

  7. Java笔记_this关键字

    this关键字 引出this的使用场景: 案例一(通过案例一来引出this的使用场景): /** * @ClassName This02 * @Description TODO * @Author O ...

  8. VMware导入ovf报错

    如下图所示报错 在网上查找了一些解决方案,大都说是ovftool版本兼容问题,但是我这里好像并不行,最后的解决的办法是对导入的位置默认不做改动. 报错原因:改变了默认路径.

  9. 个人网盘搭建SeaFile

    资料参考: https://www.ittel.cn/archives/2904.html https://www.cnblogs.com/jiuyachun/p/10185111.html  恢复和 ...

  10. 计算机科学导论-第三版-学习笔记-chapter1-绪论

    小测验的网站找不到,小程序也找不到,这两个部分的习题就不做了. Cengage Learning - Foundations of Computer Science这上面有部分答案.这里用斜体标出.我 ...