繁体   English   中英

在数据库Haskell中插入记录

[英]Insert Record in Database Haskell

我有通常可以插入数据的代码。 我有一个记录清单

让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"]]

当我尝试分解记录时,它给了我错误。 谁能帮帮我吗。 谢谢。

回应您的评论

您要做的是在将HrefLinktDes列表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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM