我有一个表,定义为
CREATE TABLE users (id SERIAL PRIMARY KEY, val BYTEA);然后,我想用binary序列化我的数据结构并存储在表中,然后检索并反序列化。
{-# LANGUAGE OverloadedStrings, DeriveAnyClass #-}
import Control.Monad (forM_)
import Data.Binary (encode, decode, Binary)
import Database.PostgreSQL.Simple
import GHC.Generics (Generic)
data User = { name :: Text, email :: Text } deriving (Show, Generic, Binary)
main = do
conn <- connect --...
let encoded = encode User {name = "me", email = "me@home.net" }
execute conn "INSERT INTO users(val) values(?)" $ Only encoded
rs <- query_ conn "SELECT id, val FROM users"
forM_ rs $ \(id,val) ->
putStrLn $ (show (id :: Int)) ++ ": " ++ show (decode val :: User)但是我得到了错误Data.Binary.Get.runGet at position 0: not enough bytes。
查询
SELECT * FROM users;给出
id | val
----+-----
1 | \x我想不出如何将ByteString%s映射到“be”。根据docs的说法,一切都应该正常。我哪里做错了?
发布于 2018-09-06 16:04:02
已通过替换行修复
execute conn "INSERT INTO users(val) values(?)" $ Only encoded使用
execute conn "INSERT INTO users(val) values(?)" $ Only $ Binary encoded这是因为toField(ByteString)生成Escape,而toField(Binary ByteString)生成EscapeByteA
https://stackoverflow.com/questions/52198898
复制相似问题