如何从管道分隔数据生成sql插件?

时间:2011-01-09 18:32:14

标签: haskell

我有一个小项目,我想尝试做 哈斯克尔。给定一组以下格式的分隔数据:

1 |星球大战:第四集 - 新希望| 1977 |行动,科幻|乔治卢卡斯 2 |泰坦尼克号| 1997 |戏剧,历史,浪漫|詹姆斯卡梅隆

在Haskell中,如何以这种格式生成sql insert语句?

插入表值(1,“星球大战:第4集 - 新希望”,1977年“,”行动,科幻“,”乔治卢卡斯“,0); 插入表值(2,“泰坦尼克号”,1997年,“戏剧,历史,浪漫”,“詹姆斯卡梅隆”,0);

为了简化问题,让我们允许参数告诉哪个 列是文本或数字。 (例如0,1,0,1,1)

这是Perl的解决方案。现在我想将Haskell添加到我的工具包中。

my @ctypes=qw/0 1 0 1 1/;

while(<>) {
  chop;
  @F=split('\|', $_);
  print "insert into table values(";
  foreach my $col (@F) {
    my $type=shift(@ctypes);
    print ($type == 1 ? '"'.$col.'"' : $col);
    print ",";
  }

  print "0);\n";
}

2 个答案:

答案 0 :(得分:4)

import Control.Arrow
import Data.List

main :: IO ()
main = interact $ unlines . map (makeInsert . splitOn '|') . lines

splitOn :: (Eq a) => a -> [a] -> [[a]]
splitOn delim = unfoldr (fmap break') . return
  where break' = second (stripPrefix [delim]) . break (== delim)

makeInsert :: [String] -> String
makeInsert parts = "insert into table values(" ++ intercalate "," values ++ ");"
  where values = zipWith ($) [id, show, id, show, show] parts ++ ["0"]

虽然您可能希望使用Data.List.Split.splitOn而不是自己编写,show不一定是引用字符串的正确方法。

答案 1 :(得分:3)

读入数据,在管道符号处拆分,正确转义所有值,并使用字符串连接来构建查询。