Skip to content

Instantly share code, notes, and snippets.

@rynmrtn
Created January 22, 2010 21:07
Show Gist options
  • Save rynmrtn/284138 to your computer and use it in GitHub Desktop.
Save rynmrtn/284138 to your computer and use it in GitHub Desktop.
Groovy script to generate insert statements from a CSV file
/**
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.
*/
// Setup basic information
tableName = "TABLE_NAME"
fileName = "C:\\file\\path"
i = 0
columns = "("
new File(fileName).splitEachLine(',') { fields ->
values = "("
if(i == 0) {
// Setup Column Names
fields.each { field ->
columns = columns + field + ","
}
columns = columns[0..(columns.length()-2)] + ")"
} else {
// Create Insert Statements with csv values
fields.collect {
values += it.equals("sysdate") ? it + "," : "'" + it + "',"
}
// Print/generate the INSERT statements
println "INSERT INTO ${tableName}${columns} VALUES${values};"
}
i++
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment