Wednesday, June 3, 2009

Export Data from Flat files to database:The Groovy way

Recently i was supposed to port a lot of data from flat files into a database. Looking at alternatives i thought it would be neat to accomplish the same using a small groovy script. Here's the crux of the script

def sql = groovy.sql.Sql.newInstance('jdbc:mysql://localhost:3306/test' ,
'root', ' ', 'com.mysql.jdbc.Driver' )
new File("C:/data/").eachFile{file->
file.eachLine{line->
def col1
def col2
def col3
def args=line.split(",")
if(args.length==3){
col1=args[0]
col2=args[1]
col3=args[2]
sql.execute"""
INSERT INTO table (col1, col2, col3)
VALUES (${col1}, ${col2}, ${col3});
"""
}
}
}


The emperor and me beaching

The Devil next door

Kaiser The Emperor