c# sqlite 批量生成insert语句的函数

函数开始

csharp 复制代码
using System;
using System.Collections.Generic;
using System.Text;

public class SqliteHelper
{
    public static List<string> GenerateInsertStatements(string tableName, List<string> columns, List<List<object>> data)
    {
        List<string> insertStatements = new List<string>();

        foreach (var row in data)
        {
            if (row.Count != columns.Count)
            {
                throw new ArgumentException("The number of columns and data items in a row must match.");
            }

            StringBuilder sb = new StringBuilder();
            sb.Append($"INSERT INTO {tableName} (");

            // Add column names
            sb.Append(string.Join(", ", columns));

            sb.Append(") VALUES (");

            // Add values
            for (int i = 0; i < row.Count; i++)
            {
                if (row[i] is string)
                {
                    sb.Append($"'{row[i]}'");
                }
                else if (row[i] is DateTime)
                {
                    sb.Append($"'{((DateTime)row[i]).ToString("yyyy-MM-dd HH:mm:ss")}'");
                }
                else
                {
                    sb.Append(row[i]);
                }

                if (i < row.Count - 1)
                {
                    sb.Append(", ");
                }
            }

            sb.Append(");");

            insertStatements.Add(sb.ToString());
        }

        return insertStatements;
    }
}

调用方式

csharp 复制代码
class Program
{
    static void Main()
    {
        string tableName = "Users";
        List<string> columns = new List<string> { "Id", "Name", "Age", "CreatedAt" };
        List<List<object>> data = new List<List<object>>
        {
            new List<object> { 1, "Alice", 25, DateTime.Now },
            new List<object> { 2, "Bob", 30, DateTime.Now },
            new List<object> { 3, "Charlie", 35, DateTime.Now }
        };

        List<string> insertStatements = SqliteHelper.GenerateInsertStatements(tableName, columns, data);

        foreach (var sql in insertStatements)
        {
            Console.WriteLine(sql);
        }
    }
}

输出

csharp 复制代码
INSERT INTO Users (Id, Name, Age, CreatedAt) VALUES (1, 'Alice', 25, '2023-10-05 12:34:56');
INSERT INTO Users (Id, Name, Age, CreatedAt) VALUES (2, 'Bob', 30, '2023-10-05 12:34:56');
INSERT INTO Users (Id, Name, Age, CreatedAt) VALUES (3, 'Charlie', 35, '2023-10-05 12:34:56');
相关推荐
晨星shine1 天前
GC、Dispose、Unmanaged Resource 和 Managed Resource
后端·c#
用户298698530141 天前
.NET 文档自动化:Spire.Doc 设置奇偶页页眉/页脚的最佳实践
后端·c#·.net
用户3667462526741 天前
接口文档汇总 - 2.设备状态管理
c#
用户3667462526741 天前
接口文档汇总 - 3.PLC通信管理
c#
Ray Liang2 天前
用六边形架构与整洁架构对比是伪命题?
java·python·c#·架构设计
Scout-leaf5 天前
WPF新手村教程(三)—— 路由事件
c#·wpf
用户298698530145 天前
程序员效率工具:Spire.Doc如何助你一键搞定Word表格排版
后端·c#·.net
mudtools6 天前
搭建一套.net下能落地的飞书考勤系统
后端·c#·.net
玩泥巴的7 天前
搭建一套.net下能落地的飞书考勤系统
c#·.net·二次开发·飞书
唐宋元明清21887 天前
.NET 本地Db数据库-技术方案选型
windows·c#