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

发布于:2025-02-18 ⋅ 阅读:(118) ⋅ 点赞:(0)

函数开始

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;
    }
}





调用方式

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);
        }
    }
}

输出

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');