c# mysql、sqlserver、Oracle、pg批量插入
在C#中,你可以使用不同的数据库访问库来实现批量插入到MySQL、SQL Server、Oracle和PostgreSQL。以下是使用Dapper
和MySql.Data
,System.Data.SqlClient
,Oracle.ManagedDataAccess.Client
和Npgsql
库进行批量插入的示例代码。
首先,确保安装了所需的NuGet包:
Install-Package Dapper
Install-Package MySql.Data
Install-Package System.Data.SqlClient
Install-Package Oracle.ManagedDataAccess.Client
Install-Package Npgsql
以下是批量插入的示例代码:
using System;
using System.Data.Common;
using Dapper;
using MySql.Data.MySqlClient;
using System.Data.SqlClient;
using Oracle.ManagedDataAccess.Client;
using Npgsql;
public class DatabaseBatchInserter
{
public void BatchInsertMySql(string connectionString, string query, IEnumerable<object> parametersList)
{
using (var connection = new MySqlConnection(connectionString))
{
connection.Open();
using (var transaction = connection.BeginTransaction())
{
foreach (var parameters in parametersList)
{
connection.Execute(query, parameters, transaction);
}
transaction.Commit();
}
}
}
public void BatchInsertSqlServer(string connectionString, string query, IEnumerable<object> parametersList)
{
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
using (var transaction = connection.BeginTransaction())
{
foreach (var parameters in parametersList)
{
connection.Execute(query, parameters, transaction);
}
transaction.Commit();
}
}
}
public void BatchInsertOracle(string connectionString, string query, IEnumerable<object> parametersList)
{
using (var connection = new OracleConnection(connectionString))
{
connection.Open();
using (var transaction = connection.BeginTransaction())
{
foreach (var parameters in parametersList)
{
connection.Execute(query, parameters, transaction);
}
评论已关闭