如何创立个人网站,外贸公司取名字大全,品牌vi设计ppt,书店建设网站有时候对于已经查询到的数据集#xff0c;想要进行二次筛选或者查询#xff0c;还得再查一遍数据库
或者其他的一些逻辑处理不太方便#xff0c;就想着为什么不能直接使用sql来查询DataTable呢#xff1f;
搜索全网没找到可用方案#xff0c;所以自己实现了一个。
主要…有时候对于已经查询到的数据集想要进行二次筛选或者查询还得再查一遍数据库
或者其他的一些逻辑处理不太方便就想着为什么不能直接使用sql来查询DataTable呢
搜索全网没找到可用方案所以自己实现了一个。
主要实现思路是使用 SQLite In-Memory Database 内存数据库
需要的包主要是
System.Data.SQLite和 SqlSugar代码如下
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using System.Linq;
using System.Text;
using System.Threading.Tasks;namespace SQLiteHelper
{public static class SQLiteHelper{public static SqlSugarClient getToSQLiteInMemorySqlSugar(DataTable dt){SQLiteConnection conn SQLiteHelper.ToSQLiteInMemory(dt);//创建配置并指定连接字符串var config new ConnectionConfig(){ConnectionString conn.ConnectionString,DbType SqlSugar.DbType.Sqlite};//创建SqlSugarClientvar db new SqlSugarClient(config);//手动指定底层连接为已有的SQLite连接db.Ado.Connection conn;return db;}private static string GetSQLiteType(Type t){if (t typeof(string)) return TEXT;else if (t typeof(int)) return INTEGER;else if (t typeof(double)) return REAL;else if (t typeof(decimal)) return NUMERIC;else return BLOB;}private static SQLiteConnection ToSQLiteInMemory(DataTable dt){// 创建SQLite in-memory数据库连接SQLiteConnection conn new SQLiteConnection(Data Source:memory:);conn.Open();// 创建表结构SQLiteCommand cmd conn.CreateCommand();string createTableSql $CREATE TABLE {dt.TableName} (;foreach (DataColumn col in dt.Columns){createTableSql ${col.ColumnName} {GetSQLiteType(col.DataType)}, ;}createTableSql createTableSql.TrimEnd(,, );createTableSql );cmd.CommandText createTableSql;cmd.ExecuteNonQuery();// 将DataTable bulk insert到SQLite表中using (SQLiteTransaction tran conn.BeginTransaction()){using (SQLiteCommand insertCmd new SQLiteCommand(conn)){insertCmd.CommandText $INSERT INTO {dt.TableName} VALUES({string.Join(,, dt.Columns.CastDataColumn().Select(x x.ColumnName))});foreach (DataRow row in dt.Rows){foreach (DataColumn col in dt.Columns){insertCmd.Parameters.AddWithValue( col.ColumnName, row[col.ColumnName]);}insertCmd.ExecuteNonQuery();insertCmd.Parameters.Clear();}tran.Commit();}}return conn;}}
}
调用示例 // 创建DataTable,添加列DataTable dt new DataTable(Products);dt.Columns.Add(Id, typeof(int));dt.Columns.Add(Name, typeof(string));dt.Columns.Add(Price, typeof(decimal));// 添加表到DataSetds.Tables.Add(dt);// 填充几行数据dt.Rows.Add(1, Apple, 1.99m);dt.Rows.Add(2, Orange, 2.99m);dt.Rows.Add(3, Banana, 0.99m);var db SQLiteHelper.getToSQLiteInMemorySqlSugar(dt);//查询结果var ret db.Ado.SqlQuerydynamic(select * from Products).ToList();
这样就实现了sql查询DataTable的功能
原创不易能帮到你的话关注评论点赞收藏走一波。