I'm new at groovy, and this is my first time writing a database connection script. It may seem like example code, but it is more like test code. It works as posted, and I'm planning to use this as a model for a larger business application, so I want to make sure I do it right.
Are there any groovy features that it could benefit from? Did I miss any edge cases, or anything else I could improve?
import groovy.sql.Sql
def dbUrl = "jdbc:postgresql://localhost/GroovyTest"
def dbUser = "Phrancis"
def dbPassword = "test"
def dbDriver = "org.postgresql.Driver"
def sql = Sql.newInstance(dbUrl, dbUser, dbPassword, dbDriver)
println "Sql Instance: " + sql
sql.execute """SET SEARCH_PATH TO groovy_test;"""
sql.execute """
START TRANSACTION;
DROP TABLE IF EXISTS test;
CREATE TABLE test (
id SERIAL,
string TEXT,
number INTEGER,
decimal NUMERIC,
datetime TIMESTAMP
);
COMMIT;"""
def params1 = ['''');DROP TABLE test;--''', 42, 3.14159, 'NOW()']
def params2 = ['Hello, World!', 99999999, 0.1209823098234, '2015-06-25']
sql.execute """
START TRANSACTION;
INSERT INTO test (string, number, decimal, datetime)
VALUES (?, ?, ?, CAST(? AS TIMESTAMP));
COMMIT;""", params1
sql.execute """
START TRANSACTION;
INSERT INTO test (string, number, decimal, datetime)
VALUES (?, ?, ?, CAST(? AS TIMESTAMP));
COMMIT;""", params2
sql.eachRow("SELECT * FROM test;") { row ->
println """
The row Id is: ${row.id}
The string is: ${row.string}
The number is: ${row.number}
The decimal is: ${row.decimal}
The date-time is: ${row.datetime}"""
}
sql.close()
Here is the stdout after this runs:
Sql Instance: groovy.sql.Sql@385c9627 The row Id is: 1 The string is: ');DROP TABLE test;-- The number is: 42 The decimal is: 3.14159 The date-time is: 2015-06-25 19:49:25.603991 The row Id is: 2 The string is: Hello, World! The number is: 99999999 The decimal is: 0.1209823098234 The date-time is: 2015-06-25 00:00:00.0 Process finished with exit code 0
"
quote in groovy when using GStrings and you can actually use them by replacing the"Sql Instance: " + sql
part with"Sql Instance: $sql"
. It surely won't make a dramatic difference, and if it is even better or worse is more of a matter of taste, but since you are just starting with groovy you can treat it as a small excercise in GStrings. \$\endgroup\$