如何使用Expr用法中的参数

时间:2010-12-13 12:40:46

标签: f#

    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)

很难解释,但我想使用useConnection中的委托conn到x.reportToDB,我该怎么办呢?

谢谢。

@Tim Robinson,是的我不知道conn那里,这是我想要解决的问题, 为什么你认为lambda在这里不好主意?

1 个答案:

答案 0 :(得分:1)

useConnection似乎需要一个MySqlConnection的函数。它为此函数提供了所需的连接对象。

修复方法是:

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

编辑:添加到useConnection功能的类型注释可能更清晰:

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