Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- @GrabConfig(systemClassLoader=true)
- @Grab(group='mysql', module='mysql-connector-java', version='5.1.+')
- import groovy.sql.Sql
- /** データベースの接続情報 */
- def getDatabaseConfig() {
- return [
- 'host': System.getenv('DB_HOST') ?: 'localhost',
- 'port': System.getenv('DB_PORT') ?: 3306,
- 'name': System.getenv('DB_NAME') ?: 'mysql',
- 'user': System.getenv('DB_USER') ?: 'root',
- 'password': System.getenv('DB_PASSWORD') ?: 'root'
- ]
- }
- /** クエリ実行 */
- def runQuery(config, query, closure) {
- def sql = null
- try {
- sql = Sql.newInstance("jdbc:mysql://${config['host']}:${config['port']}/${config['name']}",
- config['user'], config['password'],
- "com.mysql.jdbc.Driver")
- sql.query(query, closure)
- } finally {
- sql?.close()
- }
- }
- /** エスケープ処理とダブルクウォーテーションで囲う */
- def wrap(value) {
- if(value?.length() > 0){
- return '\"' + String.valueOf(value).replaceAll('\"', '\\\"') + '\"'
- }
- return ''
- }
- /** CSV用の行データを作成する */
- def makeCSVLines(query) {
- def csvLines = []
- runQuery(getDatabaseConfig(), query) { rs ->
- // header
- def columnNames = []
- def header = []
- for (i in 1 .. rs.metaData.columnCount) {
- def columnName = rs.metaData.getColumnName(i)
- columnNames << columnName
- header << wrap(columnName)
- }
- csvLines << header.join(',')
- // body
- while(rs.next()){
- def record = []
- columnNames.each {
- record << wrap(rs.getString(it))
- }
- csvLines << record.join(',')
- }
- }
- return csvLines
- }
- // 引数のチェック
- if (args.length != 2) {
- throw new IllegalArgumentException('コマンドライン引数が2つ必要です(1."クエリファイルのパス", 3."出力するCSVファイルのパス")')
- }
- // ファイル読み込み&作成
- def queryFilePath = args[0]
- def csvFilePath = args[1]
- print 'クエリファイル読み込み中...'
- def query = new File(queryFilePath).text
- println ' done'
- print 'クエリ実行中...'
- def csvLines = makeCSVLines(query)
- println ' done'
- print 'csv書き出し中...'
- def csv = new File(csvFilePath)
- csv.text = ''
- csvLines.each {
- csv.append("${it}\n")
- }
- println " done"
- println "${csvFilePath} に ${csvLines.size() - 1} 件 書き出しました。"
Add Comment
Please, Sign In to add comment