通过sqlbulk

时间:2016-03-08 14:14:43

标签: sqlbulkcopy

你好我有这样的破坏代码:

 public static void Put_CSVtoSQL_Adhesion()
    {
        bool IsFirst = true;      
        DataTable dt = new DataTable();
        string line = null;
        int i = 0;

        try
        {
            string fileName = Path.Combine(HttpContext.Current.Server.MapPath(UploadDirectory), TheFileName);

            using (StreamReader sr = File.OpenText(fileName))
            {
                while ((line = sr.ReadLine()) != null)
                {
                    string[] data = line.Split(';');
                    if (data.Length > 0)
                    {
                        if (i == 0)
                        {
                            foreach (var item in data)
                            {
                                dt.Columns.Add(new DataColumn());
                            }
                            i++;
                        }
                        DataRow row = dt.NewRow();
                        row.ItemArray = data;

                        // Pour enlever la tete 
                        if (!IsFirst) dt.Rows.Add(row);
                        IsFirst = false;
                    }
                }
            }

            using (var connectionWrapper = new Connexion())
            {
                var connectedConnection = connectionWrapper.GetConnected();
                using (SqlBulkCopy copy = new SqlBulkCopy(connectionWrapper.conn))
                {
                    int CountColl = dt.Columns.Count;

                    copy.ColumnMappings.Add(0, 1);
                    copy.ColumnMappings.Add(1, 2);
                    copy.ColumnMappings.Add(2, 3);
                    copy.ColumnMappings.Add(3, 4);
                    copy.ColumnMappings.Add(4, 5);


                    copy.DestinationTableName = "cotisation";
                    copy.WriteToServer(dt);
                }
            }
        }
        catch (Exception excThrown)
        {
            throw new Exception(excThrown.Message);
        }
    }

这段代码工作得很好,但现在我有超过60列,我应该从1到60列进行手工填写还是有另一种方法?

 copy.ColumnMappings.Add(0, 1);
                    copy.ColumnMappings.Add(1, 2);
                    copy.ColumnMappings.Add(2, 3);
                    copy.ColumnMappings.Add(3, 4);
                    copy.ColumnMappings.Add(4, 5);

...直到60列?

列完全相同我只移动了1列,因为第一列是自动增量列作为ID

1 个答案:

答案 0 :(得分:1)

写一个循环?

for (int i = 0; i < dt.Columns.Count - 1; i++)
{
    copy.ColumnMappings.Add(i, i + 1);
}