Guest User

Untitled

a guest
Feb 9th, 2019
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.42 KB | None | 0 0
  1. @GrabConfig(systemClassLoader=true)
  2. @Grab(group='mysql', module='mysql-connector-java', version='5.1.+')
  3.  
  4. import groovy.sql.Sql
  5.  
  6. /** データベースの接続情報 */
  7. def getDatabaseConfig() {
  8. return [
  9. 'host': System.getenv('DB_HOST') ?: 'localhost',
  10. 'port': System.getenv('DB_PORT') ?: 3306,
  11. 'name': System.getenv('DB_NAME') ?: 'mysql',
  12. 'user': System.getenv('DB_USER') ?: 'root',
  13. 'password': System.getenv('DB_PASSWORD') ?: 'root'
  14. ]
  15. }
  16.  
  17. /** クエリ実行 */
  18. def runQuery(config, query, closure) {
  19. def sql = null
  20. try {
  21. sql = Sql.newInstance("jdbc:mysql://${config['host']}:${config['port']}/${config['name']}",
  22. config['user'], config['password'],
  23. "com.mysql.jdbc.Driver")
  24. sql.query(query, closure)
  25. } finally {
  26. sql?.close()
  27. }
  28. }
  29.  
  30. /** エスケープ処理とダブルクウォーテーションで囲う */
  31. def wrap(value) {
  32. if(value?.length() > 0){
  33. return '\"' + String.valueOf(value).replaceAll('\"', '\\\"') + '\"'
  34. }
  35. return ''
  36. }
  37.  
  38. /** CSV用の行データを作成する */
  39. def makeCSVLines(query) {
  40. def csvLines = []
  41. runQuery(getDatabaseConfig(), query) { rs ->
  42.  
  43. // header
  44. def columnNames = []
  45. def header = []
  46. for (i in 1 .. rs.metaData.columnCount) {
  47. def columnName = rs.metaData.getColumnName(i)
  48. columnNames << columnName
  49. header << wrap(columnName)
  50. }
  51. csvLines << header.join(',')
  52.  
  53. // body
  54. while(rs.next()){
  55. def record = []
  56. columnNames.each {
  57. record << wrap(rs.getString(it))
  58. }
  59. csvLines << record.join(',')
  60. }
  61. }
  62. return csvLines
  63. }
  64.  
  65. // 引数のチェック
  66. if (args.length != 2) {
  67. throw new IllegalArgumentException('コマンドライン引数が2つ必要です(1."クエリファイルのパス", 3."出力するCSVファイルのパス")')
  68. }
  69.  
  70. // ファイル読み込み&作成
  71. def queryFilePath = args[0]
  72. def csvFilePath = args[1]
  73.  
  74. print 'クエリファイル読み込み中...'
  75. def query = new File(queryFilePath).text
  76. println ' done'
  77.  
  78. print 'クエリ実行中...'
  79. def csvLines = makeCSVLines(query)
  80. println ' done'
  81.  
  82. print 'csv書き出し中...'
  83. def csv = new File(csvFilePath)
  84. csv.text = ''
  85. csvLines.each {
  86. csv.append("${it}\n")
  87. }
  88. println " done"
  89.  
  90. println "${csvFilePath} に ${csvLines.size() - 1} 件 書き出しました。"
Add Comment
Please, Sign In to add comment