F# DataTable to SQL using SqlBulkCopy

f# sqlbulkcopy sql-server


I have an F# program that creates a DataTable, populates it with one row and then writes the data to SQL Server using bulk insert (SqlBulkCopy).

Although it's working, I can't really figure out how to include a loop that will generate a number of list items / data rows which I can then insert in one statement, rather than having to bulk insert a single row at a time (which is the current case)

here's my code:

open System
open System.Data
open System.Data.SqlClient

let lcpSqlConnection = new SqlConnection("<my-connection-string>")
let bulkLoadEsgData (conn:SqlConnection) (esgTable: list<byte * byte * int * byte * byte * single>) =
    use sbc = new SqlBulkCopy(conn, SqlBulkCopyOptions.TableLock, null, BatchSize=10000, BulkCopyTimeout=1200, DestinationTableName="dbo.myTable")
        let dt = new DataTable()
        ["Measure", typeof<byte>
        "Identifier", typeof<byte>
        "Simulation", typeof<int>
        "Time", typeof<byte>
        "Duration", typeof<byte>
         "Result", typeof<single>]
        |> List.iter (dt.Columns.Add>>ignore)

        for esgData in esgTable do
            let esg_measure, identifier, simulation, time, duration, result = esgData
            let dr = dt.NewRow()
            dr.["Measure"] <- esg_measure
            dr.["Identifier"] <- identifier
            dr.["Simulation"] <- simulation
            dr.["Time"] <- time
            dr.["Duration"] <- duration
            dr.["Result"] <- result


let myList: list<byte * byte * int * byte * byte * single> = [(byte)1,(byte)1,1, (byte)1,(byte)1,(single)0.111]

// Call method to bulk insert data row
bulkLoadEsgData lcpSqlConnection myList


I think I need to include a for loop inside the bulkLoadEsgData method, to make the code run efficiently. Except I've no idea what to do / where to write that

1/2/2013 9:23:19 PM

Accepted Answer

I managed to resolve this

    let dt = new DataTable()
    dt.Columns.Add("Measure", typeof<byte>) |> ignore
    dt.Columns.Add("Identifier", typeof<byte>) |> ignore
    dt.Columns.Add("Simulation", typeof<int>) |> ignore
    dt.Columns.Add("Time", typeof<byte>) |> ignore
    dt.Columns.Add("Duration", typeof<byte>) |> ignore
    dt.Columns.Add("Result", typeof<single>) |> ignore

    for i= 1 to 100 do
        dt.Rows.Add(i, i, i, i, i, (float)i*0.11) |> ignore

1/2/2013 9:23:32 PM

Related Questions

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow