haskell postgresql-simple,如何从更广泛的查询中访问特定数据

haskell postgresql-simple, how to access specific data from a broader query

如何访问我的查询 [VarcharIntDate] 中的数据?

data VarcharIntDate = VarcharIntDate {
  vc :: Maybe String,
  i  :: Maybe Int,
  d  :: Maybe Date
} deriving (Show)

instance FromRow VarcharIntDate where
  fromRow = VarcharIntDate <$> field <*> field <*> field

我知道如何打印它,但我不能用它做很多其他事情,因为我不知道如何处理 'IO [VarcharIntDate]'

print =<< ( query_ conn "select vc,i,d from varintdate" :: IO [VarcharIntDate] )

但我想做的是从返回的 [VarcharIntDate] 的第 n 行或所有行的 'i' 访问 'd',这样我就可以开始从查询并开始使用它。

您实际上已经处理了 IO [VarcharIntDate] 的结果。您将 =<<print 一起使用。这相当于:

main = do  -- or another function
    result <- query_ conn "select vc,i,d from varintdate" :: IO [VarcharIntDate]
    print result

您可以通过执行 mapping 或访问行的第 n 元素来处理 query_ 的结果,例如:

p = 2  -- sample p

main = do
    res <- query_ conn "select vc,i,d from varintdate" :: IO [VarcharIntDate]
    print (map i res)  -- print all i's
    print (d (res!!p)) -- print d of the p-th row

所以这里我们可以使用res!!p访问第p行,然后调用dgetter获取d那一行。

如果你想获得所有i的你可以使用map i.