Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
skeleton script for a CSV to MySQL import
#!/usr/bin/env groovy
import groovy.grape.Grape
import groovy.sql.Sql
import com.csvreader.CsvReader
@Grab(group='net.sourceforge.javacsv', module='javacsv', version='2.0')
class Import {}
[group:'mysql', module:'mysql-connector-java', version:'5.1.6', classLoader: this.class.classLoader.rootLoader]
println "connecting to DB ..."
Sql mysql = Sql.newInstance("jdbc:mysql://localhost:3306/mydb", "user", "password", "com.mysql.jdbc.Driver")
println "reading from stdin ..."
def reader = new CsvReader(new, (char) ',')
while (reader.readRecord()) {
def values = reader.values
if (values.length != 2) {
println "wrong column number ${values}"
} else {
def code = values[0]
def city = values[1]
mysql.execute("insert into buildings (code, city) values ${code}, ${city}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment