2016-05-24 180 views
1

我一直在尝试使用Npgsql版本3.1.2来实现对postgre数据库的批量插入操作,但我面临一个问题('留在消息中的数据不足') 数据类型未匹配postgre表中的列paymentdone(位(1))数据类型。我曾尝试使用bool,char,integer数据类型(C#),但也有同样的错误。在NpgSql插入位数据类型使用BeginBinaryImport批量数据插入

Code For bulk data insertion 


    public void BulkInsert(string connectionString, DataTable dataTable) 
    { 
     using (var npgsqlConn = new NpgsqlConnection(connectionString)) 
     { 
      npgsqlConn.Open(); 
      var commandFormat = string.Format(CultureInfo.InvariantCulture, "COPY {0} {1} FROM STDIN BINARY", "logging.testtable", "(firstName,LastName,LogDateTime,RowStatus,active,id,paymentdone)"); 
      using (var writer = npgsqlConn.BeginBinaryImport(commandFormat)) 
      { 
       foreach (DataRow item in dataTable.Rows) 
       { 
        writer.WriteRow(item.ItemArray); 
       } 
      } 

      npgsqlConn.Close(); 
     } 
    } 

DataTable Function 

private static void BulkInsert() 
    { 

     DataTable table = new DataTable(); 
     table.Columns.Add("firstName", typeof(String)); 
     table.Columns.Add("LastName", typeof(String)); 
     table.Columns.Add("LogDateTime", typeof(DateTime)); 
     table.Columns.Add("RowStatus", typeof(int)); 
     table.Columns.Add("active", typeof(bool)); 
     table.Columns.Add("id", typeof(long)); 
     table.Columns.Add("paymentdone", typeof(bool)); 
     var dataRow = table.NewRow(); 
     dataRow[0] = "Test"; 
     dataRow[1] = "Temp"; 
     dataRow[2] = DateTime.Now; 
     dataRow[3] = 1; 
     dataRow[4] = true; 
     dataRow[5] = 10; 
     dataRow[6] = true; 
     table.Rows.Add(dataRow); 

     BulkInsert(ConfigurationManager.ConnectionStrings["StoreEntities"].ConnectionString, table); 
    } 

回答

1

这可能是因为当Npgsql看到一个布尔值时,它的默认值是发送PostgreSQL布尔值而不是BIT(1)。当使用二进制COPY时,你必须准确写出PostgreSQL期望的类型。

一种解决方案可能是使用.NET BitArray而不是布尔值。 Npgsql会从该类型推断PostgreSQL BIT(),并且所有内容都应该可以工作。

但是一个更安全的解决方案就是简单地调用StartRow(),然后使用接受NpgsqlDbType的Write()的重载。这使您可以明确指定要发送的PostgreSQL类型。

+0

感谢它的工作 –