Groovy:解析具有特定扩展名的文件以导入MySQL,然后将其重命名为* .bak

时间:2012-11-19 10:16:56

标签: mysql file parsing groovy

我制作了一个脚本,用于连接数据库并更改特定列中的数据以确定数字。 现在我想从具有特定扩展名的文本文件中读取数字,对数据库中的这些数字进行更改,然后使用.bak扩展名重命名文件。 请帮帮我。我提前感谢您的帮助!

import groovy.sql.Sql
sql = Sql.newInstance('jdbc:mysql://localhost:3306/database', 'login', 'password', 'com.mysql.jdbc.Driver')
int rowsAffected = sql.executeUpdate('update tablename set column = '01' where number=$NumberFromFile')
println "updated: ${rowsAffected}"

2 个答案:

答案 0 :(得分:1)

这样的事情应该有效:

def newValue = '01'

new File( '/path/to/data.input' ).with { file ->
  file.withReader { reader ->
    new Scanner( reader ).useDelimiter( ';' ).with { scanner ->
      while( scanner.hasNext() ) {
        sql.executeUpdate "UPDATE tablename SET column=$newValue WHERE number=${scanner.nextInt()}"
      }
    }
  }
  file.renameTo( new File( file.parent, "${file.name}.bak" ) )
}

显然,您可能希望在事务或批处理中执行此操作,但这应该会给您提供想法

答案 1 :(得分:0)

现在我有一个脚本:

def tmn_file = ~/.*\.tmn/
def tmc_file = ~/.*\.tmc/
def newTerm = new Properties().with { props ->
    new File(inputPath).eachFile(tmn_file) { file ->
        file.withReader    { reader ->
            load( reader )
            println "Read data from file $file:"
            something read from file...
            switch( props.ACTION ) {
                case 'NEW':
                    do something...
                    }
            switch( props.ACTION ) {
                case 'CHANGE':
                    do something...
                    }

此脚本在目录中查找带有扩展名为tmn_file的路径inputPath文件,该文件可能包含ACTION - NEW或CHANGE。

脚本效果很好,但我想做另一件事:

如果文件有扩展名* .tmn(tmn_file) - 只启动带有新案例的行动

如果文件有扩展名* .tmc(tmc_file) - 仅启动带有CHANGE case的ACTION

我如何才能做出决定?