FreeSql 以 MIT 開源協(xié)議托管于 github:https://github.com/2881099/FreeSql
var connstr = "Data Source=127.0.0.1;Port=3306;User ID=root;Password=root;" +
"Initial Catalog=cccddd;Charset=utf8;SslMode=none;Max pool size=10";
static IFreeSql fsql = new FreeSql.FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.MySql, connstr)
.UseAutoSyncStructure(true) //自動(dòng)同步實(shí)體結(jié)構(gòu)到數(shù)據(jù)庫(kù)
.Build(); //請(qǐng)務(wù)必定義成 Singleton 單例模式
[Table(Name = "tb_topic")]
class Topic {
[Column(IsIdentity = true, IsPrimary = true)]
public int Id { get; set; }
public int Clicks { get; set; }
public string Title { get; set; }
public DateTime CreateTime { get; set; }
}
批量插入
var items = new List<Topic>();
for (var a = 0; a < 10; a++) items.Add(new Topic { Id = a + 1, Title = $"newtitle{a}", Clicks = a * 100 });
fsql.Insert(items).ExecuteAffrows();
執(zhí)行SQL如下:
INSERT INTO `tb_topic`(`Clicks`, `Title`, `CreateTime`)
VALUES(?Clicks0, ?Title0, ?CreateTime0),
(?Clicks1, ?Title1, ?CreateTime1),
(?Clicks2, ?Title2, ?CreateTime2),
(?Clicks3, ?Title3, ?CreateTime3),
(?Clicks4, ?Title4, ?CreateTime4),
(?Clicks5, ?Title5, ?CreateTime5),
(?Clicks6, ?Title6, ?CreateTime6),
(?Clicks7, ?Title7, ?CreateTime7),
(?Clicks8, ?Title8, ?CreateTime8),
(?Clicks9, ?Title9, ?CreateTime9)
內(nèi)部設(shè)計(jì)
當(dāng)插入大批量數(shù)據(jù)時(shí),內(nèi)部采用分割分批執(zhí)行的邏輯進(jìn)行。分割規(guī)則如下:
| 數(shù)量 | 參數(shù)量 | |
|---|---|---|
| MySql | 5000 | 3000 |
| PostgreSQL | 5000 | 3000 |
| SqlServer | 1000 | 2100 |
| Oracle | 500 | 999 |
| Sqlite | 5000 | 999 |
數(shù)據(jù):為每批分割的大小,如批量插入 10000 條數(shù)據(jù),在 mysql 執(zhí)行時(shí)會(huì)分割為兩批。
參數(shù)量:為每批分割的參數(shù)量大小,如批量插入 10000 條數(shù)據(jù),每行需要使用 5 個(gè)參數(shù)化,在 mysql 執(zhí)行時(shí)會(huì)分割為每批 3000 / 5。
分割執(zhí)行后,當(dāng)外部未提供事務(wù)時(shí),內(nèi)部自開事務(wù),實(shí)現(xiàn)插入完整性。
FreeSql 適配了每一種數(shù)據(jù)類型參數(shù)化,和不參數(shù)化的使用。批量插入建議關(guān)閉參數(shù)化功能,使用 .NonoParameter() 進(jìn)行執(zhí)行(有關(guān) NoneParameter 在后續(xù)文章介紹)。
性能參考

image
API
| 方法 | 返回值 | 參數(shù) | 描述 |
|---|---|---|---|
| AppendData | <this> | T1 | IEnumerable<T1> | 追加準(zhǔn)備插入的實(shí)體 |
| ToSql | string | 返回即將執(zhí)行的SQL語(yǔ)句 | |
| ExecuteAffrows | long | 執(zhí)行SQL語(yǔ)句,返回影響的行數(shù) | |
| ExecuteIdentity | long | 執(zhí)行SQL語(yǔ)句,返回自增值 | |
| ExecuteInserted | List<T1> | 執(zhí)行SQL語(yǔ)句,返回插入后的記錄 | |
| ExecuteSqlBulkCopy | void | SqlServer 特有的功能,執(zhí)行 SqlBulkCopy 批量插入的封裝 | |
| ExecutePgCopy | void | PostgreSQL 特有的功能,執(zhí)行 Copy 批量導(dǎo)入數(shù)據(jù) |
系列文章導(dǎo)航
(六)批量插入數(shù)據(jù)