Database Connections and F #

I wrote the following code to execute SQLServer StoredProc in F #

module SqlUtility =
  open System
  open System.Data
  open System.Data.SqlClient

  SqlUtility.GetSqlConnection "MyDB"
  |> Option.bind (fun con -> SqlUtility.GetSqlCommand "dbo.usp_MyStordProc" con) 
  |> Option.bind (fun cmd -> 
      let param1 = new SqlParameter("@User", SqlDbType.NVarChar, 50)
      param1.Value <- user
      cmd.Parameters.Add(param1) |> ignore
      let param2 = new SqlParameter("@PolicyName", SqlDbType.NVarChar, 10)
      param2.Value <- policyName
      cmd.Parameters.Add(param2) |> ignore
      Some(cmd)
    )
  |> Option.bind (fun cmd -> SqlUtility.ExecuteReader cmd)
  |> Option.bind (fun rdr -> ExtractValue rdr)         

  let GetSqlConnection (conName : string) =
    let conStr = ConfigHandler.GetConnectionString conName
    try 
      let con = new SqlConnection(conStr)
      con.Open()
      Some(con)
    with
     | :? System.Exception as ex -> printfn "Failed to connect to DB %s with Error %s "  conName ex.Message; None
     | _ -> printfn "Failed to connect to DB %s" conName; None

  let GetSqlCommand (spName : string) (con : SqlConnection) =    
    let cmd = new SqlCommand()
    cmd.Connection <- con
    cmd.CommandText <- spName
    cmd.CommandType <- CommandType.StoredProcedure
    Some(cmd)

  let AddParameters (cmd : SqlCommand) (paramList : SqlParameter list) =
    paramList |> List.iter (fun p -> cmd.Parameters.Add p |> ignore) 

  let ExecuteReader (cmd : SqlCommand ) = 
    try
      Some(cmd.ExecuteReader())
    with
    | :? System.Exception as ex -> printfn "Failed to execute reader with error %s" ex.Message; None

I have a few problems with this code

  • First of all, reusing Option.bind is very annoying ... and adds noise. I need a more understandable way to check if the output was "No", and if not, continue.

  • At the end there should be a cleanup function, where I should be able to close + dispose of the reader, command and connection. But currently, at the end of the pipeline, I only have a reader.

  • , ... , "" , - , ​​... . , .

  • Visual Studio , . ", -

downcast

, ,

let x: MyRecord seq = GetConnection "con" | > GetCommand "cmd" | > AddParameter "@name" SqlDbType.NVarchar 50 | > AddParameter "@policyname" SqlDbType.NVarchar 50 | > ExecuteReader | > FunctionToReadAndGenerateSeq | > CleanEverything

, , ?

+5
1

, langauges. F # , , .

None, - ( , None). . , , .

:

exception SqlUtilException of string

// This supports the 'printf' formatting style    
let raiseSql fmt = 
  Printf.kprintf (SqlUtilException >> raise) fmt 

.NET F #, :

// Using 'use' the 'Dispose' method is called automatically
let connName = ConfigHandler.GetConnectionString "MyDB"
use conn = new SqlConnection(connName)

// Handle exceptions that happen when opening  the connection
try conn.Open() 
with ex -> raiseSql "Failed to connect to DB %s with Error %s " connName ex.Message

// Using object initializer, we can nicely set the properties
use cmd = 
  new SqlCommand( Connection = conn, CommandText = "dbo.usp_MyStordProc",
                  CommandType = CommandType.StoredProcedure )

// Add parameters 
// (BTW: I do not think you need to set the type - this will be infered)
let param1 = new SqlParameter("@User", SqlDbType.NVarChar, 50, Value = user) 
let param2 = new SqlParameter("@PolicyName", SqlDbType.NVarChar, 10, Value = policyName) 
cmd.Parameters.AddRange [| param1; param2 |]

use reader = 
  try cmd.ExecuteReader()
  with ex -> raiseSql "Failed to execute reader with error %s" ex.Message

// Do more with the reader
()

.NET-, . F # , . F #, - ?, - :

let connName = ConfigHandler.GetConnectionString "MyDB"

// A wrapper that provides dynamic access to database
use db = new DynamicDatabase(connName)

// You can call stored procedures using method call syntax
// and pass SQL parameters as standard arguments
let rows = db.Query?usp_MyStordProc(user, policy)

// You can access columns using the '?' syntax again
[ for row in rows -> row?Column1, row?Column2 ]

. MSDN:

+7

All Articles