无法将元组或数组插入到sql表中 - 变量是ambigious

时间:2016-04-07 11:00:26

标签: postgresql haskell

我试图将一个元组或列表插入一个sql表,这样简单的不编译:

--1

newId <- execute cn "insert into mytable (var1, var2, ,) values (?, ?)" ["var1", "var2"]


--2
newId <- execute cn "insert into mytable (var1, var2, ,) values (?, ?)" ("var1", "var2")

错误是:

No instance for (ToField t0) arising from a use of ‘execute’
    The type variable ‘t0’ is ambiguous
    Note: there are several potential instances:
      instance ToField Value
        -- Defined in ‘Database.PostgreSQL.Simple.ToField’
      instance ToField a => ToField (Maybe a)
        -- Defined in ‘Database.PostgreSQL.Simple.ToField’
      instance ToField Int16
        -- Defined in ‘Database.PostgreSQL.Simple.ToField’
      ...plus 42 others
    In a stmt of a 'do' block:
      newId <- execute

1 个答案:

答案 0 :(得分:2)

当您启用OverloadedStrings时,可能会发生这种情况。使用扩展名,字符串文字的类型为IsString s => s(不是String)。 GHC很难选择ToField s的实例,因为它不知道s是什么。

当你说show . read时会发生同样的事情:没有指示GHC选择ShowRead的特定实例。

修复很简单:为文字提供类型签名。

execute sqlSnippet (["var1", "var2"] :: [Text])  -- or [String] if you really want

postgresql-simple documentation详细解释了这一点。