Skip to content

@sfussenegger /import.groovy
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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 {}
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()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.