Пример #1
0
        /// <summary>
        /// 批量插入数据
        /// </summary>
        /// <param name="tableName">目标数据库表名</param>
        /// <param name="sourceTable">源数据表</param>
        /// <param name="excludeColumnName">需排除字段</param>
        /// <returns>返回受影响的行数</returns>
        public int Insert(string tableName, DataTable sourceTable, string[] excludeColumnName)
        {
            int result;

            string[] columns = TranslateHelper.GetDataTableColumnName(sourceTable, excludeColumnName, "Insert");

            using (SqlConnection conn = new SqlConnection(ConnectionString))
            {
                conn.Open();
                SqlTransaction transaction = conn.BeginTransaction();
                SqlCommand     cmd         = conn.CreateCommand();
                cmd.CommandTimeout = Config_SqlServerDataFactory.CommandTimeout;
                cmd.Transaction    = transaction;

                try
                {
                    foreach (DataRow dr in sourceTable.Rows)
                    {
                        List <SqlParameter> parameters = new List <SqlParameter>();
                        string insertStr = DataTableTranslateHelper.DataRowToInsert(tableName, dr, columns, parameters);
                        ExecuteSQLForTransaction(cmd, insertStr, parameters.ToArray());
                    }
                    transaction.Commit();
                    result = sourceTable.Rows.Count;
                }
                catch (Exception ex)
                {
                    transaction.Rollback();
                    result = -1;
                    throw new Exception(ex.Source + ":" + ex.Message);
                }
            }
            return(result);
        }