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,我该怎么办呢?
谢谢。答案 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.