数据库
首页 > 数据库> > c#_sqlBulkCopy

c#_sqlBulkCopy

作者:互联网

#region 方法一,返回bool类型

/// <summary>
/// 该方法是讲程序中的datatable类型的数据一次性存放到数据库的临时表中,成功返回true,失败返回false
/// </summary>
/// <param name="sqlbulkCopyDT">源表</param>
/// <param name="TableName">数据库中的临时表</param>
/// <param name="strConn">连接数据库字符串</param>
/// <returns>bool</returns>    
public bool sqlbulkCopyDT(DataTable sqlbulkCopyDT, string TableName, string strConn)
{
    using (SqlConnection conn = new SqlConnection(strConn))
    {
        conn.Open();
        SqlTransaction tran = conn.BeginTransaction();

        try
        {
            if (sqlbulkCopyDT != null && sqlbulkCopyDT.Rows.Count > 0)
            {
                SqlBulkCopy bulkCopy = new SqlBulkCopy(conn, SqlBulkCopyOptions.CheckConstraints, tran);
                bulkCopy.BulkCopyTimeout = 3600;
                try
                {
                    bulkCopy.DestinationTableName = TableName;//***代表要插入数据的表名
                    foreach (DataColumn dc in sqlbulkCopyDT.Columns)  //传入上述table
                    {
                        //将table中的列与数据库表这的列一一对应
                        bulkCopy.ColumnMappings.Add(dc.ColumnName, dc.ColumnName);
                    }
                    bulkCopy.WriteToServer(sqlbulkCopyDT);
                    bulkCopy.Close();
                }
                catch (Exception ex)
                {
                    bulkCopy.Close();
                    tran.Rollback();
                    return false;
                }
            }
            tran.Commit();
            conn.Close();
        }
        catch (Exception ex)
        {
            tran.Rollback();
            conn.Close();
            return false;
        }

    }

    return true;
}

#endregion
    
    
    
    
    
    
    
    

#region 方法二 返回空类型

private void SqlBulkCopyByDatatable(string connectionString, string TableName, DataTable dt)
{
    using (SqlConnection conn = new SqlConnection(connectionString))
    {
        using (SqlBulkCopy sqlbulkcopy =
               new SqlBulkCopy(connectionString, SqlBulkCopyOptions.UseInternalTransaction))
        {
            try
            {
                sqlbulkcopy.DestinationTableName = TableName;
                for (int i = 0; i < dt.Columns.Count; i++)
                {
                    sqlbulkcopy.ColumnMappings.Add(dt.Columns[i].ColumnName, dt.Columns[i].ColumnName);
                }
                sqlbulkcopy.WriteToServer(dt);
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
        }
    }
}

#endregion

    
    
    
    

标签:bulkCopy,c#,SqlBulkCopy,sqlbulkCopyDT,tran,sqlBulkCopy,dt,conn
来源: https://www.cnblogs.com/diffknow/p/16355289.html