Haskell で SQL server に接続

Re: Help on using System.Win32.Com.Automationを参考にSQL server に ADODB 接続してみました。

module Main where

import System.Win32.Com 
import System.Win32.Com.Automation 


sqlStr  = "SELECT count(*) FROM table;"
userID  = "userName"
pass    = "password"
server  = "192.168.1.123"
db      = "dbName"

connStr = "Provider=SQLOLEDB.1;" ++
          "Password="            ++ pass   ++
          ";User ID="            ++ userID ++
          ";Initial Catalog="    ++ db     ++
          ";Data Source=tcp:"    ++ server ++ ",1433"

createConnection :: String -> IO (IDispatch a) 
createConnection dsn = do 
  c <- createObject "ADODB.Connection" 
  openConnection dsn c 
  return c 

openConnection :: String -> IDispatch a -> IO () 
openConnection dsn = method0 "Open" [inString dsn] 

closeConnection :: IDispatch a -> IO () 
closeConnection =  method0 "Close" [] 

execute :: IDispatch i -> String -> IO (IDispatch a) 
execute connection sqlStatement = 
    function_1_1 "Execute" sqlStatement connection 

eof :: IDispatch i -> IO Bool 
eof = propertyGet_0 "EOF" 

fields :: IDispatch i -> IO (IDispatch a) 
fields = propertyGet_0 "Fields" 

count :: IDispatch i -> IO Int 
count = propertyGet_0 "Count" 

moveFirst :: IDispatch i -> IO () 
moveFirst = method_0_0 "MoveFirst" 

moveNext :: IDispatch i -> IO () 
moveNext = method_0_0 "MoveNext" 

item :: IDispatch i -> Int -> IO String 
item rs key = fields rs >>= function1 "Item" [inInt key] outString 

main = coRun $ do
    coInitialize
    con <- createConnection connStr
    rs  <- execute con sqlStr
    num <- item rs 0
    putStrLn num
    closeConnection con
    coUnInitialize
    putStrLn "Done."
    return ()
PS C:\ghc\com> ghc --make com.hs
Linking com.exe ...
PS C:\ghc\com> ./com
501
Done.

COM が使えれば 「Win32OLE 活用法 【第 1 回】 Win32OLE ことはじめ」に示されているように Excel、MS-Access などがバッチリ…のはず。