Friday, August 14, 2009

Talking to mysql in Haskell

With the mysql database installed and all the other needed libraries for odbc and haskell, I can now use the haskell module HDBC.ODBC to talk to the database...

Using ghci to test some statements:

I used the function "connectODBC ...", but it resulted in a disparaging "***Exception: (unknown)".

Then I saw an example online using "handleSqlError (connectODBC ... )" which gave me the reason for the exception.

I was successful with the statement:
handleSqlError (connectODBC "DSN=my_name_from_odbc.ini_file;USER=myName;PASSWORD=myPassword")

So, time to actually run a query on my database!

I used the following program:

main = DB.handleSqlError $ do
dbh <- connectODBC "DSN=myodbc;USER=myname;PASSWORD=mypasswd; DATABASE=mydb"
res <- DB.quickQuery dbh "SELECT name FROM Mushrooms" [ ]
showRows res

showRows :: [[DB.SqlValue]] -> IO ()
showRows rows = mapM_ ioResult rows
where ioResult = (putStrLn . formatRow . fromSql)

formatRow :: [String] -> String
formatRow row = concat $ List.intersperse ", " row

fromSql :: [DB.SqlValue] -> [String]
fromSql sqlList = map DB.fromSql sqlList

No comments:

Post a Comment