开发者

How to update an SQL table with F#

I would like to update a MySQL table from an F# query. Basically I am now able to import a MySql table into a F# matrix. I am doing some calculation on this matrix through F# and after the calculation I would like to update the primary MySQL table with the new values obtained. For example let's take a开发者_如何学JAVA simple matrix coming from a MySQL table :

let m  = matrix [[1.;2.;3.];[1.;1.;3.];[3.;3.;3.]]

Now I would like to design a query which updates the mySQL table.

let query() =
  seq { use conn = new SqlConnection(connString)
        do conn.Open()
        use comm = new SqlCommand("UPDATE MyTAble SET ID = "the first column of the matrix",
                                  conn)
       }

Do I need to convert the matrix into a sequence? For this iterative update, do I need to use T-SQL (I found this way by reading some others answers?


There is no built-in functionality that would make it easier to update F# matrix in a database, so you'll have to write the update yourself. I think the best approach is to simply iterate over the matrix using for and run the update command if the value has changed. Something like:

let m1 = matrix [[1.;0.]; [0.;2.]] // The original value from DB
let m2 = m1 + m1                   // New updated matrix 

for i in 0 .. (fst m1.Dimensions) - 1 do
  for j in 0 .. (snd m1.Dimensions) - 1 do
    if m1.[i, j] <> m2.[i, j] then
      // Here you need to do the actual update
      printfn "SET %d, %d = %f" i j m2.[i, j]

Your function already shows how to run a single UPDATE command - just note that you don't need to wrap it in seq { .. } if you're not returning a sequence of results (here, you just want to perform some action).

If the number of changed values is big, then it may be useful to use some bulk update functionality (so that you don't run too many SQL commands which may be slow), but I'm not sure if MySQL has anything like that.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜