executeNamed executes a SQL statement that does not return rows, filling named placeholders from a list of NamedParam values. Its type is Connection -> Query -> [NamedParam] -> IO (). section 16.3.1
Use executeNamed when:
- The statement is an INSERT, UPDATE, or DELETE rather than a row-returning SELECT. section 16.3.1
- The SQL identifies values with named placeholders such as :checked or @checked. section 16.3.3
- The Haskell code supplies matching parameters with the (:=) syntax, such as [":id" := entryId entry]. section 16.3.3
Updating one TodoEntry
updateEntry dbConn entry = withTransaction dbConn $ executeNamed dbConn "UPDATE entries SET checked = :checked WHERE id = :id" [":checked" := checked entry, ":id" := entryId entry] The SQL names the values it needs, while the parameter list takes them from the TodoEntry. If a placeholder appears in the query without a matching parameter, executeNamed raises a FormatError exception. section 16.3.3
Listing 16.11 Functions to retrieve a TodoEntry from the database and update it
getEntryById :: Connection -> Int -> IO (Maybe TodoEntry)
getEntryById dbConn rowId = do
entries <- query dbConn "SELECT * from entries
where id = ?" (Only rowId) #1
case entries of
[x] -> return $ Just x #2
_ -> return Nothing #2
updateEntry :: Connection -> TodoEntry -> IO ()
updateEntry dbConn entry =
withTransaction dbConn $ #3
executeNamed #4
dbConn
"UPDATE entries SET checked =
:checked WHERE id = :id" #5
[":checked" := checked entry,
":id" := entryId entry] #5
Inspect the complete getEntryById and updateEntry implementation, including the transaction boundary and named parameter list. section 16.3.3
