Created
February 16, 2012 18:25
Groovy CSV to SQL
This file contains hidden or 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.sql.Sql | |
// Because of the way JDBC drivers are loaded, configure Grape to attach JDBC driver | |
// dependencies to the system class loader | |
// see http://groovy.codehaus.org/Grape | |
@GrabConfig(systemClassLoader=true) | |
@Grab(group='com.h2database', module='h2', version='1.3.163') | |
import org.h2.Driver | |
def parseCsv(filename) { | |
// Create an h2 jdbc in-memory database, | |
// calling it db1 | |
def db = Sql.newInstance("jdbc:h2:mem:db1","org.h2.Driver") | |
// Create a table from your csv file... | |
// http://www.h2database.com/html/functions.html#csvread | |
db.execute("create table people as select * from csvread('$filename')".toString()) | |
// Execute a normal sql query on this table... | |
db.eachRow("select * from people where age > 18 limit 10"){row-> | |
println row | |
} | |
} | |
// boring command line stuff | |
def parse(args) { | |
def cli = new CliBuilder(usage: 'parse_csv.groovy -[h] people.csv') | |
cli.with { | |
h longOpt: 'help', 'Show usage information' | |
} | |
def options = cli.parse(args) | |
if (!options) { | |
return | |
} | |
if (options.h || !options.arguments()) { | |
cli.usage() | |
return | |
} | |
parseCsv(options.arguments()[0]) | |
} | |
parse(args); |
This file contains hidden or 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
firstname | lastname | age | |
---|---|---|---|
alice | smith | 20 | |
bob | von und zu Lichtenberg | 19 | |
charlie | brown | 17 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment