加入若干pgsql的接口
This commit is contained in:
@@ -1,4 +1,5 @@
|
||||
using System.Data;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System.Data;
|
||||
using System.Data.SQLite;
|
||||
using static NPOI.HSSF.Util.HSSFColor;
|
||||
|
||||
@@ -263,6 +264,60 @@ namespace Ramitta
|
||||
}
|
||||
}
|
||||
|
||||
public int ExecuteBatchInsert(string tableName, List<string> columns, string columnsStr, List<Dictionary<string, object>> batch, int batchIndex)
|
||||
{
|
||||
var valueParams = new List<string>();
|
||||
var parameters = new Dictionary<string, object>();
|
||||
|
||||
for (int i = 0; i < batch.Count; i++)
|
||||
{
|
||||
var paramNames = columns.Select(col => $"@p{batchIndex}_{i}_{col}").ToList();
|
||||
valueParams.Add($"({string.Join(", ", paramNames)})");
|
||||
|
||||
foreach (var col in columns)
|
||||
{
|
||||
parameters[$"p{batchIndex}_{i}_{col}"] = batch[i][col] ?? DBNull.Value;
|
||||
}
|
||||
}
|
||||
|
||||
string insertQuery = $"INSERT INTO {tableName} ({columnsStr}) VALUES {string.Join(", ", valueParams)}";
|
||||
|
||||
using (var transaction = db.BeginTransaction())
|
||||
using (var cmd = new SQLiteCommand(insertQuery, db, transaction))
|
||||
{
|
||||
foreach (var param in parameters)
|
||||
{
|
||||
cmd.Parameters.AddWithValue(param.Key, param.Value);
|
||||
}
|
||||
|
||||
int result = cmd.ExecuteNonQuery();
|
||||
transaction.Commit();
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
// 修改主方法
|
||||
public int BulkInsert(string tableName, List<Dictionary<string, object>> dataList)
|
||||
{
|
||||
if (dataList == null || dataList.Count == 0)
|
||||
return 0;
|
||||
|
||||
int insertedCount = 0;
|
||||
var columns = dataList[0].Keys.ToList();
|
||||
var columnsStr = string.Join(", ", columns);
|
||||
int batchSize = 500;
|
||||
int batchIndex = 0; // 添加批次索引
|
||||
|
||||
for (int i = 0; i < dataList.Count; i += batchSize)
|
||||
{
|
||||
var batch = dataList.Skip(i).Take(batchSize).ToList();
|
||||
insertedCount += ExecuteBatchInsert(tableName, columns, columnsStr, batch, batchIndex);
|
||||
batchIndex++; // 递增批次索引
|
||||
}
|
||||
|
||||
return insertedCount;
|
||||
}
|
||||
|
||||
// 释放资源,关闭数据库连接
|
||||
// 确保数据库连接在对象销毁时被正确关闭
|
||||
public void Dispose()
|
||||
|
||||
Reference in New Issue
Block a user