1. 程式人生 > 實用技巧 >SqlBulkCopy批量插入資料庫

SqlBulkCopy批量插入資料庫

        /// <summary>
        /// SqlBulkCopy批量插入資料庫
        /// </summary>
        /// <param name="dtData">資料來源</param>
        /// <param name="targetTableName">目標資料表</param>
        /// <returns></returns>
        public bool SqlExcuteBulkData(DataTable dtData, string targetTableName)
        {
            bool result = false;
            using (OracleConnection conn = new OracleConnection(DBHelper.connectionString))
            {
                using (SqlBulkCopy bulkCopy = new SqlBulkCopy(DBHelper.connectionString, SqlBulkCopyOptions.Default))
                {
                    if (dtData != null && dtData.Rows.Count > 0)
                    {
                        bulkCopy.DestinationTableName = targetTableName;
                        for (int i = 0; i < dtData.Columns.Count; i++)
                        {
                            string col = dtData.Columns[i].ColumnName;
                            bulkCopy.ColumnMappings.Add(col, col);
                        }
                        conn.Open();
                        bulkCopy.WriteToServer(dtData);
                        result = true;
                    }
                }
            }
            return result;
        }