Personal tools

Cookbook/Databases access

From HaskellWiki

Jump to: navigation, search

There are two packages you can use to connect to MySQL, PostgreSQL, Sqlite3 and ODBC databases: HDBC and Hsql



2 PostgreSQL


3 SQLite

Suppose you have created a 'test.db' database like this,

$ sqlite3 test.db "create table t1 (t1key INTEGER PRIMARY KEY,data TEXT,num double,timeEnter DATE);"

$ sqlite3 test.db "insert into t1 (data,num) values ('This is sample data',3);"

$ sqlite3 test.db "insert into t1 (data,num) values ('More sample data',6);"

$ sqlite3 test.db "insert into t1 (data,num) values ('And a little more',9);"

Using HDBC and HDBC-sqlite3 packages, you can connect and query it like this:

import Control.Monad
import Database.HDBC
import Database.HDBC.Sqlite3
main = do conn <- connectSqlite3 "test.db"
          rows <- quickQuery' conn "SELECT * from t1" []
          forM_ rows $ \row -> putStrLn $ show row

$ ghc --make sqlite.hs

$ ./sqlite


[SqlString "1",SqlString "This is sample data",SqlString "3.0",SqlNull]

[SqlString "2",SqlString "More sample data",SqlString "6.0",SqlNull]

[SqlString "3",SqlString "And a little more",SqlString "9.0",SqlNull]