我的代码通常可以插入数据。我有一个记录列表
让s = [HrefInfo {link =“introduction”,description =“Introduction”},HrefInfo {link =“introduction#about-this-tutorial”,description =“关于本教程”}]
现在我想在一个数据库中插入记录,其中链接将在一列中,描述将在另一列中。
module Main(main) where
import Database.HDBC.Sqlite3
import Database.HDBC
import Database.HDBC.Types
import Database.HDBC.SqlValue
import Data.Convertible.Base
type Link = [Char]
type Description = String
type HrefLinktDes = [HrefInfo]
data HrefInfo = HrefInfo { link :: Link
, description :: Description
} deriving (Eq, Show, Read)
createDB :: IO ()
createDB = do {conn <- connectSqlite3 "ld.db";
run conn "CREATE TABLE ld (url TEXT, des TEXT)" [];
commit conn;}
storeMany :: [[String]] -> IO ()
storeMany xs =
do conn <- connectSqlite3 "ld.db"
stmt <- prepare conn "INSERT INTO ld (url, des) VALUES (?,?)"
executeMany stmt $ map (map toSql) xs
commit conn
main = do storeMany [["a","b"],["c","d"],["e","f"]]
当我试图分解记录时,它给了我错误。谁能帮帮我吗。感谢。
答案 0 :(得分:1)
回复您的comment:
您要做的是将HrefLinktDes
列表转换为[[String]]
,然后再将其传递给storeMany
。您可以通过以下方式轻松完成此任务:
hrefToList :: HrefLinktDes -> [String]
hrefToList href = [link href, description href]
您所做的只是按特定顺序将每条信息提取到列表中。您也可以使用模式匹配或RecordWildcards
扩展来执行此操作,但这一点非常简单。然后简单地
main = storeMany $ map hrefToList s
where
s = [HrefInfo {link = "introduction",
description = "Introduction"},
HrefInfo {link = "introduction#about-this-tutorial",
description = "About this tutorial"}
]
或者,您可以编写函数storeHrefs
:
storeHrefs :: [HrefInfo] -> IO ()
storeHrefs hrefs = do
conn <- connectSqlite3 "ld.db"
stmt <- prepare conn "INSERT INTO ld (url, des) VALUES (?,?)"
execMany stmt $ map (map toSql . hrefToList) hrefs
commit conn
main = storeHrefs hrefs
where
hrefs = ...
(这应该编译,但我没有检查,因为我没有安装HDBC)