mysql 批量插入BulkCopy

一、新建项目:SqlSugarDemo

  <ItemGroup>
    <PackageReference Include="SqlSugarCore" Version="5.1.3.52" />
  </ItemGroup>

二、连接串未添加AllowLoadLocalInfile=true

中文提示 : BulkCopy MySql连接字符串需要添加 AllowLoadLocalInfile=true; 添加后如果还不行Mysql数据库执行一下 SET GLOBAL local_infile=1 
English Message : connection string add : AllowLoadLocalInfile=true

show global variables like 'local_infile';

SET GLOBAL local_infile=1 

 三、Startup.cs

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WebApplication3
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton<ISqlSugarClient>(s =>
            {
                SqlSugarScope sqlSugar = new SqlSugarScope(new ConnectionConfig()
                {
                    DbType = SqlSugar.DbType.MySql,
                    ConnectionString = "Server=192.168.31.132;User ID=root;Password=123456;Database=sugar;port=3306;AllowLoadLocalInfile=true",
                    IsAutoCloseConnection = true,
                },
               db =>
               {
                   //单例参数配置,所有上下文生效
                   db.Aop.OnLogExecuting = (sql, pars) =>
                   {
                   };
               });
                return sqlSugar;
            });

            services.AddControllersWithViews();
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

HomeController.cs

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using WebApplication3.Models;

namespace WebApplication3.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;
        private readonly ISqlSugarClient _sqlSugarClient;
        public HomeController(ILogger<HomeController> logger, ISqlSugarClient sqlSugarClient)
        {
            _logger = logger;
            _sqlSugarClient = sqlSugarClient;
        }

        public IActionResult Index()
        {
            _sqlSugarClient.Fastest<RealmAuctionDatum>().BulkCopy(GetList());
            return View();
        }
        public List<RealmAuctionDatum> GetList()
        {
            var datas = new List<RealmAuctionDatum>();
            for (int i = 0; i < 10000; i++)
            {
                datas.Add(new RealmAuctionDatum { Name = Guid.NewGuid().ToString("N") });
            }
            return datas;
        }
    }
}

### C# 中实现 MySQL 批量插入 为了高效地执行批量插入操作,在 C# 和 MySQL 的组合环境中可以采用多种方法来优化性能并减少网络往返次数。一种常见的方式是利用 `MySqlBulkLoader` 类,该类专为大批量数据加载设计。 下面是一个使用 `MySqlBulkLoader` 进行批量插入的例子: ```csharp using MySql.Data.MySqlClient; // 建立连接字符串 string connectionString = "Server=localhost;Database=testdb;User ID=root;Password=example;"; var conn = new MySqlConnection(connectionString); try { // 创建文件路径和表名变量 string filePath = @"C:\path\to\yourfile.csv"; string tableName = "employees"; using (conn) { conn.Open(); var bulkCopy = new MySqlBulkLoader(conn); bulkCopy.FieldTerminator = ","; bulkCopy.Line Terminator = "\r\n"; bulkCopy.FileName = filePath; bulkCopy.TableName = tableName; bulkCopy.NumberOfLinesToSkip = 0; int rowsInserted = bulkCopy.Load(); Console.WriteLine($"{rowsInserted} 行已成功插入到 {tableName}"); } } catch (Exception ex){ Console.WriteLine($"发生错误: {ex.Message}"); } finally{ if (conn.State == System.Data.ConnectionState.Open) conn.Close(); } ``` 另一种方式则是通过构建单个 SQL 插入语句来进行多条记录的同时插入。这种方式适用于较小的数据集或当无法创建临时 CSV 文件时的情况。 以下是构建多个值列表并通过一次调用来完成大量插入的一个例子: ```csharp using MySql.Data.MySqlClient; List<string[]> dataRows = GetData(); // 获取待插入的数据集合 StringBuilder sbInsertQuery = new StringBuilder("INSERT INTO employees(name, age, position) VALUES "); foreach(var row in dataRows.Take(dataRows.Count() - 1)){ sbInsertQuery.Append($"('{row[0]}', '{row[1]}', '{row[2]}'),"); } sbInsertQuery.Append($"('{dataRows.Last()[0]}', '{dataRows.Last()[1]}', '{dataRows.Last()[2]}')"); string sqlStatement = sbInsertQuery.ToString(); using(MySqlConnection connection = new MySqlConnection(connectionString)) { MySqlCommand cmd = new MySqlCommand(sqlStatement, connection); try { connection.Open(); cmd.ExecuteNonQuery(); Console.WriteLine("所有记录都已成功插入."); } catch(Exception e){ Console.WriteLine(e.Message); } } ``` 这两种方法都能有效地提高效率,具体选择取决于应用场景和个人偏好[^1]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大熊程序猿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值