最简单的方法是使用类型提供程序,因此可以抽象出数据库。对于SQLServer,您可以使用SqlDataConnection,对于所有内容(包括SQLServer),还可以使用SqlProvider,对于SQLServer也可以使用。
这里是postgres的的dvdrental作为(样品)数据库sqlProvider的一个例子:
#r @"..\packages\SQLProvider.1.0.33\lib\FSharp.Data.SqlProvider.dll"
#r @"..\packages\Npgsql.3.1.8\lib\net451\Npgsql.dll"
open System
open FSharp.Data.Sql
open Npgsql
open NpgsqlTypes
open System.Linq
open System.Xml
open System.IO
open System.Data
let [<Literal>] dbVendor = Common.DatabaseProviderTypes.POSTGRESQL
let [<Literal>] connString1 = @"Server=localhost;Database=dvdrental;User Id=postgres;Password=root"
let [<Literal>] resPath = @"C:\Users\userName\Documents\Visual Studio 2015\Projects\Postgre2\packages\Npgsql.3.1.8\lib\net451"
let [<Literal>] indivAmount = 1000
let [<Literal>] useOptTypes = true
//create the type for the database, based on the connection string, etc. parameters
type sql = SqlDataProvider<dbVendor,connString1,"",resPath,indivAmount,useOptTypes>
//set up the datacontext, ideally you would use `use` here :-)
let ctx = sql.GetDataContext()
let actorTbl = ctx.Public.Actor //alias the table
//set up the type, in this case Records:
type ActorName = {
firstName:string
lastName:string}
//extract the data with a query expression, this gives you type safety and intellisense over SQL (but also see the SqlClient type provider above):
let qry = query {
for row in actorTbl do
select ({firstName=row.FirstName;lastName=row.LastName})
}
//seq is lazy so do all kinds of transformations if necessary then manifest it into a list or array:
qry |> Seq.toArray
的两个重要部分所定义的演员记录,然后在查询中提取的字段成的演员记录的序列。如有必要,您可以将其列入列表或数组中。
但你也可以坚持你原来的解决方案。在这种情况下,只是包装的.Read()
为seq
:
首先定义类型:
type User = {
floresID: string
exName: string
exPass: string
}
然后将解压后的数据:
let recs = cmd.ExecuteReader() // execute the SQL Command
//extract the users into a sequence of records:
let users =
seq {
while recs.Read() do
yield {floresID=recs.[0].ToString()
exName=recs.[1].ToString()
exPass=recs.[2].ToString()
}
} |> Seq.toArray
如果您已经可以从数据库中获取所需的列表,那可能是最好的方法。除此之外,您可以使用'ResizeArray <_>',这是.NET的'System.Collections.Generic.List <_>'。 'usersList'目前是一个数组,并且数组永远不会被添加到.NET中。 – TeaDrivenDev
您访问了哪个数据库,是否有使用ADO的具体原因?您应该尝试使用类型提供程序访问它。无论哪种方式,而不是一个数组尝试找回记录的seq(IEnumerable)。 – s952163