Created
November 5, 2010 09:32
-
-
Save sfussenegger/663880 to your computer and use it in GitHub Desktop.
skeleton script for a CSV to MySQL import
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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