开发者

How to use parameter from Expr usage

    let useConnection expr =
    let Expr(conn : MySqlConnection) =
        try
            try
                conn.Open()
            with
            | :? MySqlException as ex
                ->  printfn "Exception! %s" ex.Message
            expr(conn)
        finally 
            try
                conn.Close() |> ignore
            with
            | :? MySqlException as ex
                ->  printfn "Exception! %s" ex.Message
    using (new MySqlConnection(ConnectionString = 
           "server      = " + MySQLServer + ";
            uid         = " + MySQLUID + ";
            pwd         = " + MySQLPW + ";
            database    = " + MySQLDB + ";
            Charset=utf8;")) Expr

member x.reportToDB (msg:string) =
    useConnection // <--- SO HERE I WANT TO KNOW WHAT IS conn
       (let cmd = new MySqlCommand(Connection = conn)
        cmd.CommandText <- ("insert into "+MySQLTable+"(system,dt,logMessage);")
  开发者_开发知识库      ignore <| cmd.Parameters.AddWithValue("?system", Net.Dns.GetHostName())
        ignore <| cmd.Parameters.AddWithValue("?dt", DateTime.Now.ToString() )
        ignore <| cmd.Parameters.AddWithValue("?logMessage", msg )
        try
            try
                cmd.ExecuteNonQuery() |> ignore
            with
            | :? MySqlException as ex when ex.Message.Contains("Duplicate entry")
                ->  printfn "MySQL Duplicate entry Exception: discarding the data set! %s" ex.Message
                    printfn ""
            | :? MySqlException as ex
                ->  printfn "MySQL Exception, requeing data set and trying again later! %s" ex.Message
                    reraise()
        with
        | :? MySqlException as ex
            ->  printfn "Exception! %s" ex.Message)

It's hard to explain but I want to use delegate conn from useConnection to x.reportToDB , how can I do it ?

thank you.

@Tim Robinson , yes I don't know about conn there and that is a problem I want to solve, why you think that lambda is bad idea here ?


useConnection appears to want a function that takes a MySqlConnection. It supplies this function with the connection object that you want.

The fix is:

useConnection (fun conn (* here's your connection *) ->
   let cmd = new MySqlCommand(Connection = conn)
   // etc.

Edit: It's maybe clearer with type annotations added to the useConnection function:

let useConnection (expr : MySqlConnection -> 'a) : 'a =
    let Expr(conn : MySqlConnection) : 'a =
    // etc.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜