如何在f#中使用npgsql处理可能的Null值?

时间:2019-03-01 07:58:46

标签: f# npgsql

我有以下代码从证券表中获取证券列表

type Security =
    { symbol: string; exchangeId: int; name: string; firstDate: DateTime; lastDate: DateTime }

let getSecurities (conName: string) =
    // Using 'use' the 'Dispose' method is called automatically
    let conStr = 
        ConfigurationManager.ConnectionStrings.Item(conName).ConnectionString
    use conn = new NpgsqlConnection(conStr)

    // Handle exceptions that happen when opening the connection
    try conn.Open() 
    with ex -> raiseSql "Failed to connect to DB %s with Error %s " conName ex.Message

    // Using object initializer, we can nicely set the properties
    use cmd = new NpgsqlCommand()
    cmd.Connection <- conn
    cmd.CommandText <- "SELECT symbol, exchange_id, name, first_date, last_date FROM security;"

    use reader = 
        try cmd.ExecuteReader()
        with ex -> raiseSql "Failed to execute reader with error %s" ex.Message

    let results =
        [ while reader.Read() do
            yield {
                symbol = reader.GetString(reader.GetOrdinal("symbol"));
                exchangeId = reader.GetInt32(reader.GetOrdinal("exchange_id"));
                name = reader.GetString(reader.GetOrdinal("name"));
                firstDate = reader.GetDateTime(reader.GetOrdinal("first_date"));
                lastDate = reader.GetDateTime(reader.GetOrdinal("last_date"));
            } ]

    // Do more with the reader
    results

字段first_datelast_date可能具有空值。我该如何处理它们,以便我决定如果发现它们为空,该怎么办?

例如,如果发现类型为零,我可能想返回该类型的零值。或者也许我想提出一个例外情况

1 个答案:

答案 0 :(得分:0)

经过一些研究和耐心,我修改了安全记录以接受可选类型并添加了一个用于处理空值的函数

type Security =
    { symbol: string; 
        exchangeId: int; 
        name: string; 
        firstDate: DateTime option; 
        lastDate: DateTime option }

let handleNullDatesFromDb (reader: NpgsqlDataReader) (fieldName: string) =
    let ord = reader.GetOrdinal(fieldName)
    match reader.IsDBNull(ord) with
    | false -> Some (reader.GetDateTime(ord))
    | true -> None