HDBC-mysql Example
Overview
HDBC-mysql is a way to talk to mysql using Haskell. Like alot of things in Hackage, there isn't alot of demo code, so here is how I've been using it. Besides the initial connection it provides the same functions/types as the rest of HDBC.
Database Setup
Requires the following MySQL setup:
CREATE DATABASE hdbcTest; GRANT ALL ON hdbcTest.* TO hdbc@'%' IDENTIFIED BY 'hdbc'; use hdbcTest; create table test ( id INT NOT NULL AUTO_INCREMENT, PRIMARY KEY(id), value varchar(255) );
/var/run/mysqld/mysqld.sock
Change as needed.
Haskell Connection
Simple connection and test:
import Control.Monad
import Database.HDBC
import Database.HDBC.MySQL
main = do
conn <- connectMySQL defaultMySQLConnectInfo {
mysqlHost = "localhost",
mysqlPort = 3306,
mysqlUnixSocket = "/var/run/mysqld/mysqld.sock",
mysqlDatabase = "hdbcTest",
mysqlUser = "hdbc",
mysqlPassword = "hdbc"
}
rows <- quickQuery' conn "SELECT 1 + 1" []
forM_ rows $ row -> putStrLn $ show row
Something a little more complicated. Grab the count of entries, insert that count, and then spit out all the values. After the connection is established (ie the bottom of the last example).
rows <- quickQuery' conn "SELECT count(*) from test" []
run conn ("insert into test (value) values" ++
countString rows) []
rows <- quickQuery' conn "SELECT value from test" []
forM_ rows $ row -> putStrLn $ sqlValue row
That increase each time the code is ran.
Full code of the second example is available here: mysqlTest.hs
Comments(0)
2010-04-03 02:24:09