Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on May 7th, 2012  |  syntax: None  |  size: 1.68 KB  |  hits: 12  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. module DatabaseTest where
  2.  
  3. import Database.HDBC
  4. import Database.HDBC.MySQL
  5. -- cabal install MissingH
  6. import qualified Data.List.Utils as T
  7. import Control.Monad
  8.  
  9. startDb = connectMySQL defaultMySQLConnectInfo {
  10.   mysqlHost = "localhost",
  11.   mysqlDatabase = "movies",
  12.   mysqlUser = "root",
  13.   mysqlPassword = "passwd",
  14.   mysqlUnixSocket = "/var/run/mysqld/mysqld.sock"
  15. }
  16.  
  17. addMovie conn title year = do
  18.   let params = T.join "," ["title", "year"]
  19.   run conn ("INSERT INTO movies_movie (" ++ params ++ ") VALUES (?, ?)")
  20.     [toSql title, nToSql year]
  21.   commit conn
  22.  
  23.  
  24. {-
  25. [("id",SqlInt32 1),("title",SqlByteString "testing"),("year",SqlInt32 0)]
  26. [("id",SqlInt32 2),("title",SqlByteString "testing 123"),("year",SqlInt32 0)]
  27. [("id",SqlInt32 3),("title",SqlByteString "testing '123"),("year",SqlInt32 0)]
  28. [("id",SqlInt32 4),("title",SqlByteString "testing '123"),("year",SqlInt32 0)]
  29. [("id",SqlInt32 5),("title",SqlByteString "testing '123"),("year",SqlInt32 1999)]
  30. -}
  31. printMovie row = mapM_ printMovieData row
  32.  
  33. -- [("id",SqlInt32 1),("title",SqlByteString "testing"),("year",SqlInt32 0)]
  34. printMovieData row = case row of
  35.   (field, value) | field `elem` ["id"] -> print (movieId value)
  36.   (field, value) | field `elem` ["title"] -> print (movieTitle value)
  37.   _ -> return ()
  38.  
  39. movieId :: SqlValue -> Integer
  40. movieId value = do fromSql value
  41.  
  42. movieTitle :: SqlValue -> String
  43. movieTitle value = do fromSql value
  44.  
  45. main = do
  46.   conn <- startDb
  47.  
  48.   -- This is awesome I don't have to type a bunch of (),; crap!
  49.   -- addMovie conn "testing '123" 1999
  50.  
  51.   stmt <- prepare conn "SELECT * FROM movies_movie WHERE 1"
  52.   execute stmt []
  53.   results <- fetchAllRowsAL stmt
  54.   mapM_ printMovie results
  55.  
  56.   disconnect conn
  57.  
  58.   print "Done!"