您的位置:首页 > 编程语言 > C#

C#实现数据批量插入

2011-06-22 17:37 204 查看
我们在操作数据库时有的时候需要多次地重复写入数据库,那么频繁地操作数据库,必然会对数据库带来很大压力,微软提供了SqlBulkCopy类来实现批量插入,也就是当你的量保存到一定值后,再一次行写入,这样对数据库的影响就基本上降到最低了。下面是我写的一个方面,仅供大家参考,请多指正。

public static List<WeiBoMesg> weibomesg = new List<WeiBoMesg>();
/// <summary>
/// 批量插入数据
/// </summary>
/// <param name="dt">被插入表</param>
/// writer:张海平 2011-06-22
public static void BatchInsert(DataTable dt)
{
try
{
string _connKey = System.Configuration.ConfigurationManager.ConnectionStrings["conStr"].ToString();
SqlBulkCopy sqlCopy = new SqlBulkCopy(_connKey);
sqlCopy.DestinationTableName = "WeiBoMesg";
sqlCopy.ColumnMappings.Add("Contents","Contents");
sqlCopy.ColumnMappings.Add("Label","Label");
sqlCopy.ColumnMappings.Add("SmallImg","SmallImg");
sqlCopy.ColumnMappings.Add("BigImg","BigImg");
sqlCopy.ColumnMappings.Add("Date","Date");
sqlCopy.WriteToServer(dt);
sqlCopy.Close();
}
catch(Exception ex)
{
LogNet.error("BathInsert({0}):{1}");
}
}
/// <summary>
/// 把数据先存到临时表里
/// </summary>
/// writer:张海平  2011-06-22
public static void InsertTemparyTable()
{
DataTable dt = new DataTable();
dt.Columns.Add("Contents",typeof(string ));
dt.Columns.Add("Label",typeof(string));
dt.Columns.Add("SmallImg",typeof(string));
dt.Columns.Add("BigImg",typeof(string));
dt.Columns.Add("Date",typeof(DateTime));
if (weibomesg.Count > 0)
{
foreach (WeiBoMesg weibo in weibomesg)
{
DataRow row = dt.NewRow();
row["Contents"] = weibo.content;
row["Label"] = weibo.label;
row["SmallImg"] = weibo.small_pic;
row["BigImg"] = weibo.big_pic;
row["Date"] = weibo.date;
dt.Rows.Add(row);
}
weibomesg.Clear();
}
if (dt.Rows.Count > 0)
{
BatchInsert(dt);
}
}
}
public class WeiBoMesg
{
/// <summary>
/// 构造函数
/// </summary>
/// <param name="content">正文</param>
/// <param name="label">标签</param>
/// <param name="small_pic">小图片</param>
/// <param name="big_pic">大图片</param>
/// <param name="date">当前时间</param>
public WeiBoMesg(string content, string label, string small_pic, string big_pic, DateTime date)
{
this.content = content;
this.label = label;
this.small_pic = small_pic;
this.big_pic = big_pic;
this.date = date;
}
private string _content;
private string _label;
private string _small_pic;
private string _big_pic;
private DateTime _date;
public string content
{
get { return _content; }
set { _content = value; }
}
public string label
{
get { return _label; }
set { _label = value; }
}
public string small_pic
{
get { return _small_pic; }
set { _small_pic = value; }
}
public string big_pic
{
get { return _big_pic; }
set { _big_pic = value; }
}
public DateTime date
{
get { return _date; }
set { _date = value; }
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: