Using SqlBulkCopy with F# to export matrix in SQL

前端 未结 2 1768
轻奢々
轻奢々 2021-01-07 05:34

I want to transfer a large amount of data from F# to an SQL table. Basically my F# code creates a matrix of three columns (UserID, ProductID and price) and N li

2条回答
  •  耶瑟儿~
    2021-01-07 06:27

    If you're okay with third party libraries, fastmember can be really useful here.

    module DB =
        open System.Data
        open System.Data.SqlClient
        open FastMember
    
        // val bulk : conn:SqlConnection -> table:string -> columns:seq -> items:seq
        let bulk conn table columns items =        
            use bcp = new SqlBulkCopy(connection = conn)
            bcp.EnableStreaming <- true
            bcp.DestinationTableName <- table
            for n,v in columns do   
                bcp.ColumnMappings.Add(new SqlBulkCopyColumnMapping(sourceColumn = n, destinationColumn = v))               
                |> ignore
            bcp.WriteToServer(items |> ObjectReader.Create)
    

    This leaves you with a generic method that you can just funnel any seq into. Along with some config parameters, which you can of course configure to your needs.

提交回复
热议问题