public
Created

skeleton script for a CSV to MySQL import

  • Download Gist
import.groovy
Groovy
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
#!/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 {}
 
Grape.grab(
[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 java.io.InputStreamReader(System.in), (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}")
}
}
 
reader.close()
mysql.close()

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.