c# 实现sql查询DataTable数据集 对接SqlSugar ORM

有时候对于已经查询到的数据集,想要进行二次筛选或者查询,还得再查一遍数据库

或者其他的一些逻辑处理不太方便,就想着为什么不能直接使用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
            };

            //创建SqlSugarClient
            var 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.Cast<DataColumn>().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));


            // 填充几行数据
            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.SqlQuery<dynamic>("select * from Products").ToList();
           

这样就实现了sql查询DataTable的功能

原创不易,能帮到你的话,关注,评论,点赞,收藏走一波。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值