Thursday, October 29, 2009

Writing to/from a filesystem to/from a DB via Groovy

I continue to be amazed by the brevity & clarity of the Groovy language; I produced a bunch of image files from an MS Access DB with this 4-line Groovy script:

def sql = groovy.sql.Sql.newInstance("jdbc:odbc:myDSN", '', '')
sql.rows('SELECT Image_Key, Blob_Segment FROM IMAGE').each { row ->
new File("C:/tmp/pics/${row.Image_Key}.jpg").withOutputStream {OutputStream out ->
out << row.Blob_Segment
}
}

after creating an ODBC User DSN (i.e. myDSN) that pointed to the *.mdb file.

If you get an OutOfMemory error message you can simply set JAVA_OPTS from the command-line (i.e. set JAVA_OPTS="-Xmx1536m") before calling the script i.e. groovy myScript.groovy

No comments: