Finally, I get a chance to try out groovy for “real”.
Objective: Create a set of SQL queries, where a certain column holds the value of a country code. So what I needed was something like this:
insert into the-table values('the-country-code', 'some-value', 'and-more');
Looks simple enough. I already have the list of country codes in a file, separated by new-lines. All I have to do is go through the file, reading one line at a time and generate the queries. Since this was a temp job, and I only needed to save the final set of scripts, I really didn’t want to write a Java class (neither did I want to just get-it-done using Textpad). So, I thought of groovy.
I had installed groovy way back - though never quite used it. So, I fired the groovy console up and started typing - all the time missing an IDE and the fact that the console puts Vista back to Basic mode.
This is what I came up with:
import java.io.File new File("C:/1.txt").eachLine{ line -> println "insert into the-table values('" + line + "', 'some-value', 'and-more');" }
I thought this would do the trick. I would just copy paste the output to a file. Well, it kinda stopped after processing some lines (mind you, the actual SQL query that I generated was much longer than this one, so imagine flushing out huge 205 SQL queries to the console).
So, I happily took the next step and decided to write the output to another file.
import java.io.File targetFile = new File("C:/2.txt") new File("C:/1.txt").eachLine{line -> targetFile.write("insert into the-table values('" + line + "', 'some-value', 'and-more');") }
Okay, this did the trick, but all I got was ONE SQL query. ONE. 1. Okay, so .write just writes to the whole file. I needed the groovy equivalent of an append method. Again, I missed an IDE, but simply enough .append was the answer.
import java.io.File targetFile = new File("C:/2.txt") new File("C:/1.txt").eachLine{line -> targetFile.append("insert into the-table values('" + line + "', 'some-value', 'and-more');") }
Bingo, we have our queries. But all in one single long line. Let’s decorate it a bit, so that it looks a bit cleaner and slicker.
Added a new line character at the end of the query. :p
import java.io.File targetFile = new File("C:/2.txt") new File("C:/1.txt").eachLine{line -> targetFile.append("insert into the-table values('" + line + "', 'some-value', 'and-more');\n") }
Cool, isn’t it. I did one more thing so that I don’t keep appending stuff over multiple runs, and this is how my final groovy code looked like.
import java.io.File targetFile = new File("C:/2.txt") if (targetFile.exists()) targetFile.write("") new File("C:/1.txt").eachLine{line -> targetFile.append("insert into the-table values('" + line + "', 'some-value', 'and-more');\n") }
Totally zhandwa. Highly groovy.
Recent Comments