Skip to content

Instantly share code, notes, and snippets.

@rynmrtn
Forked from atonse/insert.groovy
Created January 22, 2010 21:26
Show Gist options
  • Save rynmrtn/284149 to your computer and use it in GitHub Desktop.
Save rynmrtn/284149 to your computer and use it in GitHub Desktop.
Groovy Script to Generate Insert Statements
/**
This groovy script will take a CSV file that represents the data
in a database. The first row should be the name of the columns and
all other rows should represent the data you wish to insert.
The #generate_insert function also assumes that the csv file has the
same name as the sql table that is being inserted into
*/
// Setup basic information
baseFile = "C:\\file\\path"
def generate_insert(tableName) {
i = 0
fileName = baseFile + tableName + ".csv"
new File(fileName).splitEachLine(',') { fields ->
if(i++ == 0) {
// Pull columns from first row in CSV file
columns = "(${fields.join(',')})"
} else {
// Pull each row of data and print an insert statement
values = fields.collect { it.equals("sysdate") ? it : ("'" + it + "'") }
println "INSERT INTO ${tableName}${columns} VALUES (${values.join(',')});"
}
}
}
generate_insert("table_name")
generate_insert("another_table_name")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment