Guest User

Untitled

a guest
Jun 17th, 2018
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.49 KB | None | 0 0
  1. // g100pon #44 DBとテーブル名を引数指定して標準入力から読み取ったCSV/TSVデータをinsert
  2.  
  3. import groovy.sql.Sql
  4. import groovy.grape.Grape
  5.  
  6. if(args.size()<2){
  7. println "Usage: groovy Text2DB.groovy <DB> <TABLE> < <CSV|TSV>"
  8. System.exit(1)
  9. }
  10.  
  11. def dbName = args[0]
  12. def tableName = args[1]
  13. println "[DB]$dbName, [TABLE]$tableName"
  14.  
  15. // JDBCドライバの取得とGroovySQLクラスのセットアップ
  16. Grape.grab(group:'org.apache.derby', module:'derby', version:'[10.5.3,)',
  17. classLoader:this.class.classLoader.rootLoader)
  18. def sql = Sql.newInstance("jdbc:derby:memory:${dbName};create=true",
  19. 'user', 'password', 'org.apache.derby.jdbc.EmbeddedDriver')
  20.  
  21. // テーブル作成(簡単のため。不要であれば削除。)
  22. sql.execute("""create table ${tableName} (
  23. id integer not null primary key,
  24. firstname varchar(20),
  25. lastname varchar(20),
  26. location_id integer,
  27. location_name varchar(30)
  28. )""".toString())
  29.  
  30. // INSERT文の定義
  31. def insertStmt = """
  32. insert into ${tableName}
  33. values (?, ?, ?, ?, ?)
  34. """
  35.  
  36. // 標準入力からテキストを読み込んでリストに変換
  37. def data = parseText(System.in.text)
  38.  
  39. // INSERT実行
  40. data.each{
  41. sql.execute insertStmt, it
  42. }
  43.  
  44. // 実行結果確認
  45. sql.eachRow("select * from ${tableName}".toString()){ println it}
  46.  
  47.  
  48. // 簡易CSV/TSVパーサー
  49. def parseText(String text){
  50. def separator = ','
  51. if(text.contains('\t')) separator = '\t'
  52.  
  53. def data = []
  54. text.eachLine{
  55. data << it.tokenize(separator)
  56. }
  57. return data
  58. }
Add Comment
Please, Sign In to add comment