Data.List.Splitを使うと簡単にCSVをリストに変換出来ます。
split パッケージをインストールします。
> cabal update Downloading the latest package list from hackage.haskell.org > cabal install split Resolving dependencies... Downloading split-0.1.2.3... (snip) Registering split-0.1.2.3...
> :m + Data.List.Split -- CSV のファイルを読み込みます。 > f <- readFile "jyusho_mst.csv" -- 改行ごとにリストに取り込み、その先頭。 > (lines f) !! 0 --=> "0,hoge,\255,123-4567,0,0,00001,1,0,0,0,0,0" -- その行を","を区切りとしてリストに変換 > splitOn "," $ (lines f) !! 0 --=> ["0","hoge","\255","123-4567","0","0","00001","1","0","0","0","0","0"] > putStrLn $ (splitOn "," $ (lines f) !! 0) !! 1 --=> hoge
CSV ファイルから INSERT 文を作ります。
import Data.List.Split -- CSV ファイルを読み込んで INSERT文に変換したのを書き込む。 csvToINSERT = do csv <- readFile "./jyusho_mst1.csv" writeFile "./jyusho_mst1.sql" $ sqlString csv -- CSV String から INSERT INTO の文字列を作る sqlString :: String -> String sqlString = unlines . foldr (\ls out -> toInsertSql ls out) [] . delNullLine -- CSV String からリストに変換する関数を行ごとに適用。 delNullLine :: String -> [[String]] delNullLine csv = foldr (\str out -> deleteIF str out) [] (lines csv) -- CSV String をリストに変換。リスト2番目の要素(ls !! 1)が " " は削除 deleteIF :: String -> [[String]] -> [[String]] deleteIF str out = if (ls !! 1) == " " then out else ls:out where ls = splitOn "," str -- リストから INSERT 文を作る。 -- out は foldr の蓄積。 toInsertSql :: [String] -> [String] -> [String] toInsertSql ls out = concat ["INSERT INTO jusho_mst ", " VALUES (nextval('jusho_mst_id_seq'),", code,",",name,",",kana,",",post,",",memo,");"] : out where code = ls !! 0 name = quote $ ls !! 1 kana = "''" post = quote $ ls !! 3 memo = "''" quote s = "'" ++ s ++ "'" {- $ cat jyusho_mst1.sql INSERT INTO jusho_mst VALUES (nextval('jusho_mst_id_seq'),1,'hoge','','123-0002',''); INSERT INTO jusho_mst VALUES (nextval('jusho_mst_id_seq'),2,'huga','','123-0012',''); (snip) -}