简体   繁体   中英

Insert Record in Database Haskell

I have code which can generally insert data. I have a record list

let s = [HrefInfo {link = "introduction", description = "Introduction"},HrefInfo {link = "introduction#about-this-tutorial", description = "About this tutorial"}]

Now I want to insert record s in a database where link will be in one column, description will be in another column.

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

When I try to break down the record it gives me error. Can anyone please help me. Thanks.

In response to your comment :

What you'll want to do is convert your list of HrefLinktDes to [[String]] before passing it to storeMany . You can do this pretty easily with:

hrefToList :: HrefLinktDes -> [String]
hrefToList href = [link href, description href]

All you're doing is extracting each piece of information into the list in a specific order. You can also do this with pattern matching or the RecordWildcards extension, too, but this one is pretty straightforward. Then simply

main = storeMany $ map hrefToList s
    where
        s = [HrefInfo {link = "introduction",
                       description = "Introduction"},
             HrefInfo {link = "introduction#about-this-tutorial",
                       description = "About this tutorial"}
            ]

Alternatively, you could write a function 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 = ...

(This should compile, but I haven't checked because I don't have HDBC installed)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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