[英]Transfer a MySQL table into a F# matrix
我想将仅包含整数的SQL表(假设i。2列:一列包含用户ID,一列包含用户age和ii。n行)转移到F#矩阵(相同尺寸)中。 我设法使用下面的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
如果您事先不知道矩阵的大小,可以使用多种方法来初始化矩阵。 例如, Matrix.ofList
获取列表列表,并自动计算大小。
如果只有UserDatabaseList
(可以在不知道行数和列数的情况下创建),那么您应该能够编写:
Matrix.ofList
[ // Create list containing rows from the database
for row in UserDatabaseList do
// For each row, return list of columns (float values)
yield [ float row.ID; float row.Age ] ]
另外-F#矩阵确实非常有用,主要是如果您要执行一些矩阵运算(即使那样,它也不是最有效的选择)。 如果您要进行一些数据处理,则将数据保存在普通列表中可能会更容易。 如果您正在做一些严肃的数学运算,则可能需要检查如何使用F#中的Math.NET库 ,该库具有更有效的矩阵类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.