繁体   English   中英

F#从CSV生成SQL

[英]F# Generate SQL from CSV

我最近一直在学习F#和函数式编程。 我发现一个非常有用的应用程序是从带有一些相关ID的CSV(或excel表)中为数据加载生成SQL插入。

以下代码是我的结果,我相信我将来会发现它非常方便。 我认为其他人也可以从中受益,我欢迎人们在他们的收藏中发现宝贵的建议和其他脚本:

// Returns some dataload SQL for area mapping.
open System
open System.IO

// Read and split CSV into lists
let map_ngo_area = File.ReadAllLines(@"P:\MY_TABLE.csv") 
                        |> Array.to_list
                        |> List.map(fun x -> (x.Split([|','|]) 
                                                |> Array.map(fun y -> y.Trim())) 
                                                |> Array.to_list)

// Output Formatting function
let format_sql_record = "INSERT INTO MyTable
     (ID, REF1_ID, REF2_ID, CreatedUser, CreatedDateTime, LastModifiedUser, LastModifiedDateTime)
     VALUES
     ( {0}, {1}, {2}, 'system', getDate(), 'system', getDate() )"

 // Generate the SQL for the given list.  
let generate_sql list = list |> List.mapi(fun index row -> 
                                            match row with
                                                | [ngo_id; area_id] -> String.Format(format_sql_record, ((int index)+1), ngo_id, area_id) |> printfn "%s"
                                                | _ -> printfn "")

// Main Execution
map_ngo_area |> generate_sql |> ignore

// End of program, pause to view console output.
System.Console.ReadKey() |> ignore

有关改进我的F#代码或流程的任何建议? 评论也很受欢迎,因为我在这个范例中相当新,而且转变思维并不像我预期的那样即将到来。

谢谢 :)

以下是一些建议:

  • 不要将List.mapi与返回unit函数一起使用,因为对结果unit list不多。 您应该使用List.iteri ,这将允许您在主执行部分的末尾省略|> ignore
  • 更进一步,不是让generate_sql打印一个生成的行,而是生成一个字符串列表可能更好。 请注意,在这种情况下,您将返回使用List.mapi因为您应用的函数将返回每行的结果。
  • 使用F#的打印格式而不是String.Format 例如,不要让format_sql_record成为字符串,让它是int->string->string->string类型的函数: let format_sql_record = sprintf "INSERT INTO ... VALUES (%i, %s, %s, ...)"
  • 根据您正在使用的F#版本,您可能应该使用重命名的函数Array.toList而不是Array.to_list ,因为这是将在F#的最终版本中使用的名称。

您也可以在数组上使用模式匹配:

let map_ngo_area = File.ReadAllLines(@"P:\MY_TABLE.csv") 
                    |> Array.to_list
                    |> List.map(fun x -> (x.Split([|','|]) 
                                            |> Array.map(fun y -> y.Trim())) 

let generate_sql list = list |> List.mapi(fun index row -> 
                                            match row with
                                            | [| ngo_id; area_id |] -> printfn ...
                                            | _ -> printfn "")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM