如何在F#中处理空值

时间:2015-09-20 12:04:21

标签: f# f#-data

我正在尝试从下面的MS访问中获取数据(类型:double)。下面的A& B中存储了多个空值。有没有办法将这些空值更改为零?

let query sql w= 
seq{
let conn = new OleDbConnection( @"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=Portfolio.accdb;
Persist Security Info=False;" )
conn.Open()
let DAdapter = new OleDbDataAdapter(sql,conn)
let DTable = new DataSet()
let i= DAdapter.Fill(DTable)
let rowCol = DTable.Tables.[0].Rows
let rowCount = rowCol.Count
for i in 0 .. (rowCount - 1) do
           yield w (rowCol.[i]) 
       }
type Table1= {  
                    A:double;
                    B:double} 



let cf=query "SELECT * FROM T" (fun row -> 
      {  
         A=unbox(row.["A"]);
         B=unbox(row.["B"]);})

2 个答案:

答案 0 :(得分:4)

定义一个函数

let toFloat = function
    | null -> 0.0
    | obj -> unbox obj

然后按如下方式使用

let cf = query "SELECT * FROM T" (fun row -> 
      {  A = toFloat row.["A"]
         B = toFloat row.["B"] } )

答案 1 :(得分:1)

也许,您在DB中的列具有不同的类型(例如,int和double)。或者尝试使用DBNull类型检查返回值:

let toDouble x = 
    if System.Convert.IsDBNull(x) then 0.0
    else System.Double.Parse(x.ToString())

要检查我是否创建了该表:

enter image description here

使用您的代码:

open System.Data
open System.Data.OleDb

let toDouble x = 
    if System.Convert.IsDBNull(x) then 0.0
    else System.Double.Parse(x.ToString())

let query sql w= 
    seq{
        let conn = new OleDbConnection( @"Provider=Microsoft.ACE.OLEDB.12.0;
                    Data Source=F:/Portfolio.accdb;Persist Security Info=False;" )
        conn.Open()
        let DAdapter = new OleDbDataAdapter(sql,conn)
        let DTable = new DataSet()
        let i = DAdapter.Fill(DTable)
        let rowCol = DTable.Tables.[0].Rows
        let rowCount = rowCol.Count
        for i in 0 .. (rowCount - 1) do
                yield w (rowCol.[i]) 
        conn.Close()
       }

type Table1= {  A:double; B:double } 

let cf = query "SELECT * FROM T" (fun row -> {  A = toDouble row.["A"]; B = toDouble row.["B"] } )

cf |> Seq.iter(fun x -> printfn "%A" x)

结果:

{A = 1.0;
 B = 2.2;}
{A = 3.0;
 B = 0.0;}
{A = 4.0;
 B = 0.0;}