使用SqlBulkCopy将F#DataTable转换为SQL [英] F# DataTable to SQL using SqlBulkCopy
问题描述
我有一个F#程序,该程序创建一个DataTable
,将其填充为一行,然后使用批量插入(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)
这是我的代码:
open System
open System.Data
open System.Data.SqlClient
let lcpSqlConnection = new SqlConnection("<my-connection-string>")
lcpSqlConnection.Open()
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")
sbc.WriteToServer(
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
dt.Rows.Add(dr)
dt)
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
lcpSqlConnection.Close()
我认为我需要在bulkLoadEsgData
方法内部包括一个for循环,以使代码高效运行.除了我不知道该做什么/在哪里写
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
推荐答案
我设法解决了
sbc.WriteToServer(
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
dt)
这篇关于使用SqlBulkCopy将F#DataTable转换为SQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!