我现在正试图找出一种从 F# 插入 SQL Server 的方法。
我有一个 F# 函数,它按照用户定义的模式循环访问文件夹内的所有文件。然后我可以使用返回的数据放入列表或(理想情况下)插入数据库。
我已经有一个可以正常工作的 insert-into-sql 函数:
let execNonQuery conn s =
let comm =
new SqlCeCommand(s, conn)
try
comm.ExecuteNonQuery() |> ignore
with e ->
printf "Error : %A\n" e
let string = "insert into MyTable (MyColumn) values ('test .. again')"
execNonQuery conn string; // works
我正在尝试让这个方法正常工作:
let rec getAllFiles dir pattern =
seq { yield! Directory.EnumerateFiles(dir, pattern)
for d in Directory.EnumerateDirectories(dir) do
yield! getAllFiles d pattern }
let getApplications (dir : string) (extension : string) =
getAllFiles dir extension
//|> Seq.toList // If I need to create a list of returned values
|> Seq.iter (fun s -> SQLInsertString s) // This does not work as it complains about the function not being of type unit
如果我仅使用 Seq.toList
并按以下方式调用该函数,它会起作用:
getApplications "C:\Admin" "*.txt" // works
我不明白的另一件事是如何创建一个有效的插入命令,该命令接受一个字符串作为值。例如:
let SQLInsertString s = "insert into MyTable (MyColumn) values (%s)" //does not work
最佳答案
你快到了。问题是 sqlInsertString
返回 string
,这在 Seq.iter
中使用是不合法的。
您使用 sqlInsertString
所做的是使用字符串格式创建一个字符串。它非常适合 sprintf
函数:
let sqlInsertString s =
sprintf "insert into MyTable (MyColumn) values (%s)" s
现在您可以对 sqlInsertString
的结果使用 execNonQuery
将数据实际插入数据库。由于 execNonQuery
返回 unit
,它可以很容易地在 Seq.iter
中使用:
// Assuming conn is a global and already defined variable.
let getApplications (dir : string) (extension : string) =
getAllFiles dir extension
|> Seq.iter (fun s -> execNonQuery conn (sqlInsertString s))
由于类型注释是多余的,您的代码可以用更惯用的方式重写:
let getApplications dir extension conn =
getAllFiles dir extension
|> Seq.iter (sqlInsertString >> execNonQuery conn)
关于sql - F# 将列表插入 SQL Server,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9295436/