我想將只包含整數的SQL表格(比如說包含用戶ID的一列和包含用戶年齡和ii。n行的一列)轉換爲F#矩陣(相同的尺寸)。 我設法用下面的F#代碼來實現,但我相信這不是最有效的方式。將一個MySQL表格轉換爲F#矩陣
事實上,我發現定義F#矩陣的唯一方法是使用MySQL創建2個帶有單個值(分別爲行數和列數)的表格,並將這些值轉換爲F#。
是否有可能通過F#代碼將「mySQL」表導入F#矩陣,該代碼「識別」矩陣的維度。基本上我想要一個函數,它將表地址作爲參數並返回一個矩陣。
這裏是我的代碼:
#r "FSharp.PowerPack.dll"
#r "Microsoft.Office.Interop.Excel"
open System
open System.Data
open System.Data.SqlClient
open Microsoft.Office.Interop
open Microsoft.FSharp.Math
open System.Collections.Generic
//Need of three types : User, number of rows and number of columns
type user = {
ID : int;
Age : int;}
type nbrRows = {NbreL : int ;}
type nbrCol = {NbreC : int ;}
// I. Import the SQL data into F#
// I.1. Import the number of rows of the table into F#
let NbrRows = seq {
use cnn = new SqlConnection(@"myconnection; database=MyDataBase; integrated security=true")
use cmd1 = new SqlCommand("Select * from theTablesWhichContainsTheNumberOfRows", cnn)
cnn.Open()
use reader = cmd1.ExecuteReader()
while reader.Read() do
yield {
NbreL = unbox(reader.["Expr1"])
}
}
let NbrRowsList = NbrRows |> Seq.toList // convert the sequence into a List
// I.2. Same code to import the number of columns of the table
let NbrCol = seq {
use cnn = new SqlConnection(@"MyConnection; database=myDatabase; integrated security=true")
use cmd1 = new SqlCommand("Select * from theTablesWhichContainsTheNumberOfColumns", cnn)
cnn.Open()
use reader = cmd1.ExecuteReader()
while reader.Read() do
yield {
NbreC = unbox(reader.["Expr1"])
}
}
let NbrColsList = NbrCol |> Seq.toList
// Initialisation of the Matrix
let matrixF = Matrix.create NbrRowsList.[0].NbreL NbrColsList.[0].NbreC 0.
//Transfer of the mySQL User table into F# through a sequence as previously
let GetUsers = seq {
use cnn = new SqlConnection(@"myConnection, database=myDatabase; integrated security=true")
use cmd = new SqlCommand("Select * from tableUser ORDER BY ID", cnn)
cnn.Open()
use reader = cmd.ExecuteReader()
while reader.Read() do
yield {
ID = unbox(reader.["ID"])
Age = unbox(reader.["Age"])
}
}
// Sequence to list
let UserDatabaseList = GetUsers |> Seq.toList
// Fill of the user matrix
for i in 0 .. (NbrRowList.[0].NbreL - 1) do
matrixF.[0,i] <- UserDatabaseList.[i].ID |> float
matrixF.[1,i] <- UserDatabaseList.[i].Age|> float
matrixUsers
謝謝托馬斯,它非常清晰,看起來不錯。 – fabco63