2015-01-29 2 views
1

sqlbulkcopy를 SQL 테이블에 연결하려고합니다. 내 데이터 테이블에있는 소스는 3 개의 열과 대상 테이블에 4 개의 열이 있고 첫 번째 열은 idendity 열입니다. 대상 테이블은 레코드가 데이터베이스에 삽입 될 때 값을 생성합니다. 다음 코드 줄에서 "주어진 ColumnMapping이 소스 또는 대상의 모든 열과 일치하지 않습니다."라는 메시지를 표시합니다. sqlBulkCopy.WriteToServer (dtExcelData); 나는 그 문제가 무엇인지 이해하지 못한다.Sql bulkcopy error - 주어진 ColumnMapping이 소스 또는 대상의 모든 열과 일치하지 않습니다.

이드 (INT) ACCOUNTNUMBER (VARCHAR 9) 금액 (소수점 11,2) Sedol (NVARCHAR 30)

XSSFWorkbook xssfwb; 
      using (FileStream file = new FileStream(excelPath, FileMode.Open, FileAccess.Read)) 
      { 
       xssfwb = new XSSFWorkbook(file); 
      } 


      var sheet = xssfwb.GetSheetAt(0); // Change this to the worksheet you want to import. 
      var rows = sheet.GetRowEnumerator(); 
      var dtExcelData = new DataTable(); 
      var linenumber = 0; 
      DataRow dr; 



      dtExcelData.Columns.AddRange(new DataColumn[3] { 
      new DataColumn("AccountNumber", typeof(string)), 
      new DataColumn("Amount", typeof(decimal)), 
      new DataColumn("Sedol",typeof(string)) }); 



      while (rows.MoveNext()) 
      { 
       IRow row = (XSSFRow)rows.Current; 
       linenumber++; 


       row.GetCell(4).SetCellType(CellType.Numeric); 

       if (row.GetCell(0) != null) 
       { 
        dr = dtExcelData.NewRow(); 
        dr["AccountNumber"] = row.GetCell(1).ToString(); 
        //dr["Amount"] = decimal.Parse(row.GetCell(4).ToString()); 
        dr["Amount"] = (decimal)row.GetCell(4).NumericCellValue; 
         dr["Sedol"] = row.GetCell(11).ToString(); 


        dtExcelData.Rows.Add(dr); 
       } 
      } 

      DealingContext.ExecuteCommand("TRUNCATE TABLE [dbDealing].[MESSAGING].[Rebate]"); 



      //Set the database table name 
      //using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(DealingContext.Connection.ConnectionString,SqlBulkCopyOptions.KeepIdentity)) 
      using (SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(DealingContext.Connection.ConnectionString)) 
      { 
       sqlBulkCopy.DestinationTableName = "[dbDealing].[MESSAGING].[Rebate]"; 


       //[OPTIONAL]: Map the Excel columns with that of the database table 
       sqlBulkCopy.ColumnMappings.Add("AccountNumber", "Owning Account ID"); 
       sqlBulkCopy.ColumnMappings.Add("Amount", "Amount"); 
       sqlBulkCopy.ColumnMappings.Add("Sedol", "Related Asset Identifier value"); 
       sqlBulkCopy.WriteToServer(dtExcelData); 

      } 
+0

나는 또한이 오류가 있었고 내가 삽입 한 테이블의 일부 기본 제약 조건을 제거했을 때 사라졌습니다. 매우 이상합니다. – John

답변

0

I를 다음과 같이

처 테이블 데이터 유형

은 이전에는 문제가 있었어.

처음에는이 클래스를 사용합니다. (인터넷이 아니기 때문에 오래 전에 인터넷에서 발견되었고 조금 수정되었습니다.) 두 번째로 올바른 테이블을 채우고 있는지 확인하십시오.

public static class BulkCopy 
{ 
    public static DataTable ToDataTable<T>(List<T> data) 
    { 
     PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T)); 
     DataTable table = new DataTable(); 

     if (IdentityColumnName != null) 
     { 
      if (IdentityColumnType == "int") 
       table.Columns.Add(IdentityColumnName, typeof(Int32)); 
      else if (IdentityColumnType == "string") 
       table.Columns.Add(IdentityColumnName, typeof(string)); 
     } 

     for (int i = 0; i < props.Count; i++) 
     { 
      PropertyDescriptor prop = props[i]; 
      table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType); 
     } 


     if (IdentityColumnName != null) 
     { 
      object[] values = new object[props.Count + 1]; 
      foreach (T item in data) 
      { 
       for (int i = 1; i < values.Length; i++) 
       { 
        values[i] = props[i - 1].GetValue(item) ?? DBNull.Value; 
       } 

       table.Rows.Add(values); 
      } 
     } 
     else 
     { 
      object[] values = new object[props.Count]; 
      foreach (T item in data) 
      { 
       int i = 0; 
       for (i = 0; i < values.Length; i++) 
       { 
        values[i] = props[i].GetValue(item) ?? DBNull.Value; 
       } 

       table.Rows.Add(values); 
      } 
     } 
     return table; 
    } 

    public static void BulkSqlInsert<T>(List<T> list, string tableName,string connectionString) 
    { 
     if (list == null) 
      throw new Exception("List of " + typeof(T).ToString() + " is null!"); 

     BulkCopy.BulkSqlInsert(BulkCopy.ToDataTable<T>(list), tableName, connectionString); 
    } 

    public static void BulkSqlInsert(DataTable dt, string tableName, string connectionString) 
    { 
     if (dt.Rows.Count == 0) 
      return; 

     using (SqlConnection connection = new SqlConnection(connectionString)) 
     { 
      SqlBulkCopy bulkCopy = 
       new SqlBulkCopy 
       (
       connection, 
       SqlBulkCopyOptions.TableLock | 
       SqlBulkCopyOptions.FireTriggers | 
       SqlBulkCopyOptions.UseInternalTransaction, 
       null 
       ); 


      bulkCopy.DestinationTableName = tableName; 

      connection.Open(); 


      bulkCopy.WriteToServer(dt); 
      connection.Close(); 
     } 
    } 

    public static string IdentityColumnName { get; set; } 

    public static string IdentityColumnType { get; set; }//string or int 


} 

예 :

당신은 3 열 색상 및 무게와 하나의 ID 열 테이블 (CAR)가 ID를 가정 해 봅시다.

이 클래스를 만듭니다

public class BulkCopyCar 
{ 
    public string Color { get; set; } 

    public string Weight{ get; set; } 
} 

채우기 BulkCopyCar :

List<BulkCopyCar> bulkCopyCarList = new List<BulkCopyCar>(); 
      bulkCopyCarList.Add(new BulkCopyCar() { Color = "Red", Weight = 155 }); 
      bulkCopyCarList.Add(new BulkCopyCar() { Color = "Blue", Weight = 400 }); 

삽입 데이터베이스에 :

BulkCopy.IdentityColumnName = "ID"; 
      BulkCopy.IdentityColumnType = "int"; 
      BulkCopy.BulkSqlInsert(bulkCopyCarList, "CAR", SQLConnectionString); 

당신은 ID 열 사용을 바로이 라인이없는 경우 :

BulkCopy.BulkSqlInsert(bulkCopyCarList, "CAR", SQLConnectionString); 
+0

나는 이것을 시도하고 ID 컬럼을 가지고 있지 않은 다른 테이블과 그것을 시험해 보았다. 나는 문제가 identity 컬럼에 있다고 생각한다. 어떻게 sqlbulkcopy에 내 테이블에 ID 컬럼이 있는지 알려 주겠다. – user3751248

+0

그래서 기존 테이블과 새로운 테이블을 망가 뜨리려 고 노력했다. 따라서 ID 컬럼과 관련이있다. – user3751248

+0

See my 예 : BulkCopy.IdentityColumnName = "ID"; BulkCopy.IdentityColumnType = "int" –

관련 문제