- /// <summary>
- /// 初始化一个DataTable类型的数据源
- /// <para/>Author : AnDequan
- /// <para/>Date : 2011-3-14
- /// </summary>
- /// <returns>Source</returns>
- private DataTable InitSource()
- {
- DataTable dtUserAdd = new DataTable();
- dtUserAdd.Columns.Add(new DataColumn("ID", typeof(int)));
- dtUserAdd.Columns.Add(new DataColumn("UserName", typeof(string)));
- dtUserAdd.Columns.Add(new DataColumn("UserPwd", typeof(string)));
- DataRow drTemp = null;
- for (int i = 0; i < 100; i++)
- {
- drTemp = dtUserAdd.NewRow();
- drTemp["ID"] = 0;
- drTemp["UserName"] = "测试" + (i + 1);
- drTemp["UserPwd"] = "密码" + (i + 1);
- dtUserAdd.Rows.Add(drTemp);
- }
- return dtUserAdd;
- }
- /// <summary>
- /// 一次性把DataTable中的数据插入<a href="http://lib.csdn.net/base/mysql" class='replace_word' title="MySQL知识库" target='_blank' style='color:#df3434; font-weight:bold;'>数据库</a>
- /// <para/>Author : AnDequan
- /// <para/>Date : 2011-3-14
- /// </summary>
- /// <param name="source">DataTable数据源</param>
- /// <returns>true - 成功,false - 失败</returns>
- public bool AddDataTableToDB(DataTable source)
- {
- SqlTransaction tran = null;//声明一个事务对象
- try
- {
- using (SqlConnection conn = new SqlConnection("server=.;uid=sa;pwd=sa;database=Test;"))
- {
- conn.Open();//打开链接
- using (tran = conn.BeginTransaction())
- {
- using (SqlBulkCopy copy = new SqlBulkCopy(conn, SqlBulkCopyOptions.Default, tran))
- {
- copy.DestinationTableName = "AnDequan.dbo.[User]"; //指定服务器上目标表的名称
- copy.WriteToServer(InitSource()); //执行把DataTable中的数据写入DB
- tran.Commit(); //提交事务
- return true; //返回True 执行成功!
- }
- }
- }
- }
- catch (Exception ex)
- {
- if (null != tran)
- tran.Rollback();
- //LogHelper.Add(ex);
- return false;//返回False 执行失败!
- }
- }
一次性把DataTable中的数据插入数据库
最新推荐文章于 2024-07-03 14:41:03 发布