mysql批量插入数据的基类

自己设计的一个mysql数据库批量添加数据的基类。用于批量向mysql数据库添加数据,子类实现起来很简单,自测性能也还不错。

1、基类实现-BatchAddBase

 using System.Collections.Generic;
using System.Text; namespace MysqlBatchAdd
{
public abstract class BatchAddBase<T> where T : class, new()
{
/// <summary>
/// 插入语句的头部
/// </summary>
protected abstract string InsertHead { get; } /// <summary>
/// 出入语句的执行体
/// </summary>
protected List<string> InsertBodyList { get; set; } = new List<string>();
/// <summary>
/// 缓存的sql语句长度
/// </summary>
public int SqlCacheLengh { get; set; } = * ; /// <summary>
/// 批量添加的方法
/// </summary>
/// <param name="m"></param>
public abstract void BatchAdd(T m); /// <summary>
/// 执行添加
/// </summary>
public virtual void ExecuteBatchAdd()
{
StringBuilder sqlCache = new StringBuilder(); foreach (string insertBody in InsertBodyList)
{
sqlCache.Append(insertBody + ","); if (sqlCache.Length >= SqlCacheLengh)
{
sqlCache.Remove(sqlCache.Length - , );
MySqlHelper.ExecuteNonQuery(this.InsertHead + sqlCache.ToString());
sqlCache.Clear();
}
} if (sqlCache.Length > )
{
sqlCache.Remove(sqlCache.Length - , );
MySqlHelper.ExecuteNonQuery(this.InsertHead + sqlCache.ToString());
sqlCache.Clear();
}
}
/// <summary>
/// 清楚缓存
/// </summary>
public void ClearInsertBody()
{
this.InsertBodyList.Clear();
}
}
}

2、一个简单的子类实现-PersonAddHelper

 namespace MysqlBatchAdd
{
public class PersonAddHelper : BatchAddBase<Person>
{
protected override string InsertHead
{
get
{
return @"insert into person(
name) values ";
}
} public override void BatchAdd(Person m)
{
this.InsertBodyList.Add($@" (
'{m.name}')");
}
}
}

3、控制台项目,使用示例

 static void Main(string[] args)
{
PersonAddHelper personAddHelper = new PersonAddHelper(); Stopwatch watch = new Stopwatch(); watch.Start(); int amount = ; for (int i = ; i <= amount; i++)
{
personAddHelper.BatchAdd(new Person() { name = i + "号" });
} personAddHelper.ExecuteBatchAdd(); watch.Stop(); Console.WriteLine($"成功插入 {amount} 条数据,用时:{watch.ElapsedMilliseconds} ms"); Console.ReadKey();
}

4、源码示例地址:http://files.cnblogs.com/files/renjing/MysqlBatchAdd.rar

上一篇:jQuery尺寸算法


下一篇:Web开发人员不容错过的10个HTML5工具