A facade over Java's normal JDBC APIs providing greatly simplified resource management and result set handling. Under the covers the facade hides away details associated with getting connections, constructing and configuring statements, interacting with the connection, closing resources and logging errors. Special features of the facade include using closures to iterate through result sets, a special GString syntax for representing prepared statements and treating result sets like collections of maps with the normal Groovy collection methods available.
newInstance factory methods available to do this.
In simple cases, you can just provide
the necessary details to set up a connection (e.g. for hsqldb):
def db = [url:'jdbc:hsqldb:mem:testDB', user:'sa', password:'', driver:'org.hsqldb.jdbc.JDBCDriver'] def sql = Sql.newInstance(db.url, db.user, db.password, db.driver)or if you have an existing connection (perhaps from a connection pool) or a datasource use one of the constructors:
def sql = new Sql(datasource)Now you can invoke sql, e.g. to create a table:
sql.execute '''
create table PROJECT (
id integer not null,
name varchar(50),
url varchar(100),
)
'''
Or insert a row using JDBC PreparedStatement inspired syntax:
def params = [10, 'Groovy', 'http://groovy.codehaus.org'] sql.execute 'insert into PROJECT (id, name, url) values (?, ?, ?)', paramsOr insert a row using GString syntax:
def map = [id:20, name:'Grails', url:'http://grails.codehaus.org'] sql.execute "insert into PROJECT (id, name, url) values ($map.id, $map.name, $map.url)"Or a row update:
def newUrl = 'http://grails.org' def project = 'Grails' sql.executeUpdate "update PROJECT set url=$newUrl where name=$project"Now try a query using
eachRow:
println 'Some GR8 projects:'
sql.eachRow('select * from PROJECT') { row ->
println "${row.name.padRight(10)} ($row.url)"
}
Which will produce something like this:
Some GR8 projects: Groovy (http://groovy.codehaus.org) Grails (http://grails.org) Griffon (http://griffon.codehaus.org) Gradle (http://gradle.org)Now try a query using
rows:
def rows = sql.rows("select * from PROJECT where name like 'Gra%'")
assert rows.size() == 2
println rows.join('\n')
with output like this:
[ID:20, NAME:Grails, URL:http://grails.org] [ID:40, NAME:Gradle, URL:http://gradle.org]Also,
eachRow and rows support paging. Here's an example:
sql.eachRow('select * from PROJECT', 2, 2) { row ->
println "${row.name.padRight(10)} ($row.url)"
}
Which will start at the second row and return a maximum of 2 rows. Here's an example result:
Grails (http://grails.org) Griffon (http://griffon.codehaus.org)Finally, we should clean up:
sql.close()If we are using a DataSource and we haven't enabled statement caching, then strictly speaking the final
close() method isn't required - as all connection
handling is performed transparently on our behalf; however, it doesn't hurt to
have it there as it will return silently in that case.
If instead of newInstance you use withInstance, then
close() will be called automatically for you.
sql.firstRow('select * from PersonTable')
This example is potentially at risk of SQL injection:
sql.firstRow('select * from PersonTable where SurnameColumn = ' + userInput)
This in turn will be fine if 'userInput' is something like 'Smith' but maybe
not so fine if 'userInput' is something like 'Smith; DROP table PersonTable'.
Instead, use one of the variants with parameters and placeholders:
sql.firstRow("select * from PersonTable where SurnameColumn = ?", [userInput])
or the GString variants which will be converted to the placeholder variants under the covers:
sql.firstRow("select * from PersonTable where SurnameColumn = $userInput")
or the named parameter variants discussed next.
| Modifiers | Name | Description |
|---|---|---|
protected class |
Sql.AbstractQueryCommand |
| Modifiers | Name | Description |
|---|---|---|
static OutParameter |
ARRAY |
|
static OutParameter |
BIGINT |
|
static OutParameter |
BINARY |
|
static OutParameter |
BIT |
|
static OutParameter |
BLOB |
|
static OutParameter |
BOOLEAN |
|
static OutParameter |
CHAR |
|
static OutParameter |
CLOB |
|
static OutParameter |
DATALINK |
|
static OutParameter |
DATE |
|
static OutParameter |
DECIMAL |
|
static OutParameter |
DISTINCT |
|
static OutParameter |
DOUBLE |
|
static OutParameter |
FLOAT |
|
static OutParameter |
INTEGER |
|
static OutParameter |
JAVA_OBJECT |
|
protected static Logger |
LOG |
Hook to allow derived classes to access the log |
static OutParameter |
LONGVARBINARY |
|
static OutParameter |
LONGVARCHAR |
|
static OutParameter |
NULL |
|
static OutParameter |
NUMERIC |
|
static OutParameter |
OTHER |
|
static OutParameter |
REAL |
|
static OutParameter |
REF |
|
static OutParameter |
SMALLINT |
|
static OutParameter |
STRUCT |
|
static OutParameter |
TIME |
|
static OutParameter |
TIMESTAMP |
|
static OutParameter |
TINYINT |
|
static OutParameter |
VARBINARY |
|
static OutParameter |
VARCHAR |
| Constructor and description |
|---|
Sql
(DataSource dataSource)Constructs an SQL instance using the given DataSource. |
Sql
(Connection connection) |
Sql
(Sql parent) |
| Type | Name and description |
|---|---|
static InParameter |
ARRAY(Object value) |
static InParameter |
BIGINT(Object value) |
static InParameter |
BINARY(Object value) |
static InParameter |
BIT(Object value) |
static InParameter |
BLOB(Object value) |
static InParameter |
BOOLEAN(Object value) |
static InParameter |
CHAR(Object value) |
static InParameter |
CLOB(Object value) |
static InParameter |
DATALINK(Object value) |
static InParameter |
DATE(Object value) |
static InParameter |
DECIMAL(Object value) |
static InParameter |
DISTINCT(Object value) |
static InParameter |
DOUBLE(Object value) |
static InParameter |
FLOAT(Object value) |
static InParameter |
INTEGER(Object value) |
static InParameter |
JAVA_OBJECT(Object value) |
static InParameter |
LONGVARBINARY(Object value) |
static InParameter |
LONGVARCHAR(Object value) |
static InParameter |
NULL(Object value) |
static InParameter |
NUMERIC(Object value) |
static InParameter |
OTHER(Object value) |
static InParameter |
REAL(Object value) |
static InParameter |
REF(Object value) |
static InParameter |
SMALLINT(Object value) |
static InParameter |
STRUCT(Object value) |
static InParameter |
TIME(Object value) |
static InParameter |
TIMESTAMP(Object value) |
static InParameter |
TINYINT(Object value) |
static InParameter |
VARBINARY(Object value) |
static InParameter |
VARCHAR(Object value) |
protected List |
asList(String sql, ResultSet rs)Hook to allow derived classes to override list of result collection behavior. |
protected List |
asList(String sql, ResultSet rs, Closure metaClosure) |
protected List |
asList(String sql, ResultSet rs, int offset, int maxRows, Closure metaClosure) |
protected String |
asSql(GString gstring, List values)Hook to allow derived classes to override sql generation from GStrings. |
protected SqlWithParams |
buildSqlWithIndexedProps(String sql) |
void |
cacheConnection(Closure closure) |
void |
cacheStatements(Closure closure)Caches every created preparedStatement in Closure closure Every cached preparedStatement is closed after closure has been called. |
int |
call(String sql) |
int |
call(GString gstring) |
int |
call(String sql, List params) |
int |
call(String sql, Object[] params)Performs a stored procedure call with the given parameters. |
void |
call(String sql, List params, Closure closure) |
void |
call(GString gstring, Closure closure) |
List |
callWithRows(GString gstring, Closure closure) |
List |
callWithRows(String sql, List params, Closure closure) |
protected List |
callWithRows(String sql, List params, boolean processResultSet, Closure closure) |
SqlWithParams |
checkForNamedParams(String sql, List params) |
void |
close()If this SQL object was created with a Connection then this method closes the connection. |
protected void |
closeResources(Connection connection, Statement statement, ResultSet results)An extension point allowing derived classes to change the behavior of resource closing. |
protected void |
closeResources(Connection connection, Statement statement) |
protected void |
closeResources(Connection connection)Provides a hook for derived classes to be able to configure JDBC statements. |
void |
commit() |
protected void |
configure(Statement statement) |
protected Connection |
createConnection()An extension point allowing derived classes to change the behavior of connection creation. |
protected Sql.AbstractQueryCommand |
createPreparedQueryCommand(String sql, List queryParams) |
protected Sql.AbstractQueryCommand |
createQueryCommand(String sql)Stub needed for testing. |
DataSet |
dataSet(String table) |
DataSet |
dataSet(Class type) |
void |
eachRow(String sql, Closure closure) |
void |
eachRow(String sql, int offset, int maxRows, Closure closure) |
void |
eachRow(String sql, Closure metaClosure, Closure rowClosure) |
void |
eachRow(String sql, Closure metaClosure, int offset, int maxRows, Closure rowClosure) |
void |
eachRow(String sql, List params, Closure metaClosure, int offset, int maxRows, Closure rowClosure)Performs the given SQL query calling the given rowClosure with each row of the result set starting at
the provided offset, and including up to maxRows number of rows.
|
void |
eachRow(String sql, Map map, Closure metaClosure, int offset, int maxRows, Closure rowClosure)A variant of eachRow(String, java.util.List, groovy.lang.Closure, int, int, groovy.lang.Closure) allowing the named parameters to be supplied in a map. |
void |
eachRow(Map map, String sql, Closure metaClosure, int offset, int maxRows, Closure rowClosure) |
void |
eachRow(String sql, List params, Closure metaClosure, Closure rowClosure) |
void |
eachRow(String sql, Map params, Closure metaClosure, Closure rowClosure) |
void |
eachRow(Map params, String sql, Closure metaClosure, Closure rowClosure) |
void |
eachRow(String sql, List params, Closure closure) |
void |
eachRow(String sql, Map params, Closure closure) |
void |
eachRow(Map params, String sql, Closure closure) |
void |
eachRow(String sql, List params, int offset, int maxRows, Closure closure) |
void |
eachRow(String sql, Map params, int offset, int maxRows, Closure closure) |
void |
eachRow(Map params, String sql, int offset, int maxRows, Closure closure) |
void |
eachRow(GString gstring, Closure metaClosure, Closure rowClosure) |
void |
eachRow(GString gstring, Closure metaClosure, int offset, int maxRows, Closure rowClosure) |
void |
eachRow(GString gstring, int offset, int maxRows, Closure closure) |
void |
eachRow(GString gstring, Closure closure) |
boolean |
execute(String sql) |
boolean |
execute(String sql, List params)Executes the given piece of SQL with parameters. |
boolean |
execute(Map params, String sql)A variant of execute(String, java.util.List) useful when providing the named parameters as named arguments. |
boolean |
execute(String sql, Object[] params) |
boolean |
execute(GString gstring) |
List |
executeInsert(String sql) |
List |
executeInsert(String sql, List params)Executes the given SQL statement (typically an INSERT statement). |
List |
executeInsert(Map params, String sql)A variant of firstRow(String, java.util.List) useful when providing the named parameters as named arguments. |
List |
executeInsert(String sql, Object[] params) |
List |
executeInsert(GString gstring) |
protected ResultSet |
executePreparedQuery(String sql, List params) |
protected ResultSet |
executeQuery(String sql)Useful helper method which handles resource management when executing a query which returns a result set. |
int |
executeUpdate(String sql) |
int |
executeUpdate(String sql, List params)Executes the given SQL update with parameters. |
int |
executeUpdate(Map params, String sql)A variant of executeUpdate(String, java.util.List) useful when providing the named parameters as named arguments. |
int |
executeUpdate(String sql, Object[] params) |
int |
executeUpdate(GString gstring) |
static ExpandedVariable |
expand(Object object)When using GString SQL queries, allows a variable to be expanded in the Sql string rather than representing an sql parameter. |
protected int |
findWhereKeyword(String sql)Hook to allow derived classes to override where clause sniffing. |
GroovyRowResult |
firstRow(String sql) |
GroovyRowResult |
firstRow(GString gstring)Performs the given SQL query and return the first row of the result set. |
GroovyRowResult |
firstRow(String sql, List params) |
GroovyRowResult |
firstRow(Map params, String sql)A variant of firstRow(String, java.util.List) useful when providing the named parameters as named arguments. |
GroovyRowResult |
firstRow(String sql, Object[] params) |
Connection |
getConnection() |
DataSource |
getDataSource()If this SQL object was created with a Connection then this method commits the connection. |
protected List |
getParameters(GString gstring)Hook to allow derived classes to override behavior associated with extracting params from a GString. |
int |
getResultSetConcurrency()Gets the resultSetConcurrency for statements created using the connection. |
int |
getResultSetHoldability()Gets the resultSetHoldability for statements created using the connection. |
int |
getResultSetType()Gets the resultSetType for statements created using the connection. |
int |
getUpdateCount()@return Returns the updateCount. |
List |
getUpdatedParams(List params, List indexPropList)@return boolean true if caching is enabled (the default is true) |
static InParameter |
in(int type, Object value) |
static InOutParameter |
inout(InParameter in)Create an inout parameter using this in parameter. |
boolean |
isCacheNamedQueries() |
boolean |
isCacheStatements()Caches the connection used while the closure is active. |
boolean |
isEnableNamedQueries() |
boolean |
isWithinBatch()Returns true if the current Sql object is currently executing a withBatch method call. |
static void |
loadDriver(String driverClassName)Attempts to load the JDBC driver on the thread, current or system class loaders |
static Sql |
newInstance(String url)Creates a new Sql instance given a JDBC connection URL. |
static Sql |
newInstance(String url, Properties properties)Creates a new Sql instance given a JDBC connection URL and some properties. |
static Sql |
newInstance(String url, Properties properties, String driverClassName)Creates a new Sql instance given a JDBC connection URL, some properties and a driver class name. |
static Sql |
newInstance(String url, String user, String password)Creates a new Sql instance given a JDBC connection URL, a username and a password. |
static Sql |
newInstance(String url, String user, String password, String driverClassName)Creates a new Sql instance given a JDBC connection URL, a username, a password and a driver class name. |
static Sql |
newInstance(String url, String driverClassName)Creates a new Sql instance given a JDBC connection URL and a driver class name. |
static Sql |
newInstance(Map args)Creates a new Sql instance given parameters in a Map. |
protected String |
nullify(String sql)Hook to allow derived classes to override null handling. |
static OutParameter |
out(int type)Create a new OutParameter |
SqlWithParams |
preCheckForNamedParams(String sql) |
void |
query(String sql, Closure closure) |
void |
query(String sql, List params, Closure closure)Performs the given SQL query, which should return a single ResultSet object. |
void |
query(String sql, Map map, Closure closure)A variant of query(String, java.util.List, groovy.lang.Closure) useful when providing the named parameters as a map. |
void |
query(Map map, String sql, Closure closure) |
void |
query(GString gstring, Closure closure) |
static ResultSetOutParameter |
resultSet(int type)Create a new ResultSetOutParameter |
void |
rollback()If this SQL object was created with a Connection then this method rolls back the connection. |
List |
rows(String sql) |
List |
rows(String sql, int offset, int maxRows) |
List |
rows(String sql, Closure metaClosure) |
List |
rows(String sql, int offset, int maxRows, Closure metaClosure) |
List |
rows(String sql, List params)Performs the given SQL query and return the rows of the result set. |
List |
rows(Map params, String sql) |
List |
rows(String sql, List params, int offset, int maxRows) |
List |
rows(String sql, Map params, int offset, int maxRows) |
List |
rows(Map params, String sql, int offset, int maxRows) |
List |
rows(String sql, Object[] params) |
List |
rows(String sql, Object[] params, int offset, int maxRows) |
List |
rows(String sql, List params, Closure metaClosure) |
List |
rows(String sql, Map params, Closure metaClosure) |
List |
rows(Map params, String sql, Closure metaClosure) |
List |
rows(String sql, List params, int offset, int maxRows, Closure metaClosure) |
List |
rows(String sql, Map params, int offset, int maxRows, Closure metaClosure)A variant of rows(String, java.util.List, int, int, groovy.lang.Closure) useful when providing the named parameters as a map. |
List |
rows(Map params, String sql, int offset, int maxRows, Closure metaClosure) |
List |
rows(GString sql, int offset, int maxRows) |
List |
rows(GString gstring) |
List |
rows(GString gstring, Closure metaClosure) |
List |
rows(GString gstring, int offset, int maxRows, Closure metaClosure)Performs the given SQL query and return a "page" of rows from the result set. |
void |
setCacheNamedQueries(boolean cacheNamedQueries) |
void |
setCacheStatements(boolean cacheStatements)@return boolean true if cache is enabled (default is false) |
void |
setEnableNamedQueries(boolean enableNamedQueries) |
protected void |
setInternalConnection(Connection conn) |
protected void |
setObject(PreparedStatement statement, int i, Object value) |
protected void |
setParameters(List params, PreparedStatement statement)Strategy method allowing derived classes to handle types differently such as for CLOBs etc. |
void |
setResultSetConcurrency(int resultSetConcurrency)Sets the resultSetConcurrency for statements created using the connection. |
void |
setResultSetHoldability(int resultSetHoldability)Sets the resultSetHoldability for statements created using the connection. |
void |
setResultSetType(int resultSetType)Sets the resultSetType for statements created using the connection. |
int[] |
withBatch(Closure closure) |
int[] |
withBatch(int batchSize, Closure closure) |
int[] |
withBatch(String sql, Closure closure)Performs the closure (containing batch operations specific to an associated prepared statement) within a batch. |
int[] |
withBatch(int batchSize, String sql, Closure closure) |
static void |
withInstance(String url, Closure c)Invokes a closure passing it a new Sql instance created from the given JDBC connection URL. |
static void |
withInstance(String url, Properties properties, Closure c)Invokes a closure passing it a new Sql instance created from the given JDBC connection URL and properties. |
static void |
withInstance(String url, Properties properties, String driverClassName, Closure c)Invokes a closure passing it a new Sql instance created from the given JDBC connection URL, properties and driver classname. |
static void |
withInstance(String url, String user, String password, Closure c)Invokes a closure passing it a new Sql instance created from the given JDBC connection URL, user and password. |
static void |
withInstance(String url, String user, String password, String driverClassName, Closure c)Invokes a closure passing it a new Sql instance created from the given JDBC connection URL. |
static void |
withInstance(String url, String driverClassName, Closure c)Invokes a closure passing it a new Sql instance created from the given JDBC connection URL. |
static void |
withInstance(Map args, Closure c)Invokes a closure passing it a new Sql instance created from the given map of arguments. |
void |
withStatement(Closure configureStatement)Enables statement caching. |
void |
withTransaction(Closure closure)Performs the closure within a transaction using a cached connection. |
Hook to allow derived classes to access the log
Constructs an SQL instance using the given DataSource. Each operation will use a Connection from the DataSource pool and close it when the operation is completed putting it back into the pool.
dataSource - the DataSource to useHook to allow derived classes to override list of result collection behavior. The default behavior is to return a list of GroovyRowResult objects corresponding to each row in the ResultSet.
sql - query to executers - the ResultSet to processmetaClosure - called for meta data (only once after sql execution)Hook to allow derived classes to override sql generation from GStrings.
gstring - a GString containing the SQL query with embedded paramsvalues - the values to embedCaches every created preparedStatement in Closure closure Every cached preparedStatement is closed after closure has been called. If the closure takes a single argument, it will be called with the connection, otherwise it will be called with no arguments.
closure - the given closurePerforms a stored procedure call with the given parameters.
An Object array variant of call(String, List).
sql - the SQL statementparams - an array of parametersIf this SQL object was created with a Connection then this method closes the connection. If this SQL object was created from a DataSource then this method only frees any cached objects (statements in particular).
An extension point allowing derived classes to change the behavior of resource closing.
connection - the connection to closestatement - the statement to closeresults - the results to closeProvides a hook for derived classes to be able to configure JDBC statements. Default behavior is to call a previously saved closure, if any, using the statement as a parameter.
statement - the statement to configureAn extension point allowing derived classes to change the behavior of connection creation. The default behavior is to either use the supplied connection or obtain it from the supplied datasource.
Stub needed for testing. Called when a connection is opened by one of the command-pattern classes so that a test case can monitor the state of the connection through its subclass.
conn - the connection that is about to be used by a command Performs the given SQL query calling the given rowClosure with each row of the result set starting at
the provided offset, and including up to maxRows number of rows.
The row will be a GroovyResultSet which is a ResultSet
that supports accessing the fields using property style notation and ordinal index values.
In addition, the metaClosure will be called once passing in the
ResultSetMetaData as argument.
The query may contain placeholder question marks which match the given list of parameters.
Note that the underlying implementation is based on either invoking ResultSet.absolute(),
or if the ResultSet type is ResultSet.TYPE_FORWARD_ONLY, the ResultSet.next() method
is invoked equivalently. The first row of a ResultSet is 1, so passing in an offset of 1 or less has no effect
on the initial positioning within the result set.
Note that different database and JDBC driver implementations may work differently with respect to this method.
Specifically, one should expect that ResultSet.TYPE_FORWARD_ONLY may be less efficient than a
"scrollable" type.
sql - the sql statementparams - a list of parametersoffset - the 1-based offset for the first row to be processedmaxRows - the maximum number of rows to be processedmetaClosure - called for meta data (only once after sql execution)rowClosure - called for each row with a GroovyResultSetA variant of eachRow(String, java.util.List, groovy.lang.Closure, int, int, groovy.lang.Closure) allowing the named parameters to be supplied in a map.
sql - the sql statementmap - a map containing the named parametersoffset - the 1-based offset for the first row to be processedmaxRows - the maximum number of rows to be processedmetaClosure - called for meta data (only once after sql execution)rowClosure - called for each row with a GroovyResultSetExecutes the given piece of SQL with parameters. Also saves the updateCount, if any, for subsequent examination.
Example usage:
sql.execute """
insert into PERSON (id, firstname, lastname, location_id) values (?, ?, ?, ?)
""", [1, "Guillaume", "Laforge", 10]
assert sql.updateCount == 1
This method supports named and named ordinal parameters. See the class Javadoc for more details.
Resource handling is performed automatically where appropriate.
sql - the SQL statementparams - a list of parameterstrue if the first result is a ResultSet
object; false if it is an update count or there are
no resultsA variant of execute(String, java.util.List) useful when providing the named parameters as named arguments.
params - a map containing the named parameterssql - the SQL statementtrue if the first result is a ResultSet
object; false if it is an update count or there are
no resultsExecutes the given SQL statement (typically an INSERT statement). Use this variant when you want to receive the values of any auto-generated columns, such as an autoincrement ID field. The query may contain placeholder question marks which match the given list of parameters. See executeInsert(GString) for more details.
This method supports named and named ordinal parameters. See the class Javadoc for more details.
Resource handling is performed automatically where appropriate.
sql - The SQL statement to executeparams - The parameter values that will be substituted
into the SQL statement's parameter slotsA variant of firstRow(String, java.util.List) useful when providing the named parameters as named arguments.
params - a map containing the named parameterssql - The SQL statement to executeUseful helper method which handles resource management when executing a query which returns a result set. Derived classes of Sql can override "createQueryCommand" and then call this method to access the ResultSet returned from the provided query or alternatively can use the higher-level method of Sql which return result sets which are funnelled through this method, e.g. eachRow, query.
sql - query to executeExecutes the given SQL update with parameters.
This method supports named and named ordinal parameters. See the class Javadoc for more details.
Resource handling is performed automatically where appropriate.
sql - the SQL statementparams - a list of parametersA variant of executeUpdate(String, java.util.List) useful when providing the named parameters as named arguments.
params - a map containing the named parameterssql - the SQL statementWhen using GString SQL queries, allows a variable to be expanded in the Sql string rather than representing an sql parameter.
Example usage:
def fieldName = 'firstname'
def fieldOp = Sql.expand('like')
def fieldVal = '%a%'
sql.query "select * from PERSON where ${Sql.expand(fieldName)} $fieldOp ${fieldVal}", { ResultSet rs ->
while (rs.next()) println rs.getString('firstname')
}
// query will be 'select * from PERSON where firstname like ?'
// params will be [fieldVal]
object - the object of interestHook to allow derived classes to override where clause sniffing. Default behavior is to find the first 'where' keyword in the sql doing simple avoidance of the word 'where' within quotes.
sql - the SQL statementPerforms the given SQL query and return the first row of the result set. The query may contain GString expressions.
Example usage:
def location = 25
def ans = sql.firstRow("select * from PERSON where location_id < $location")
println ans.firstname
Resource handling is performed automatically where appropriate.
gstring - a GString containing the SQL query with embedded paramsnull if no row is foundA variant of firstRow(String, java.util.List) useful when providing the named parameters as named arguments.
params - a map containing the named parameterssql - the SQL statementnull if no row is foundIf this SQL object was created with a Connection then this method commits the connection. If this SQL object was created from a DataSource then this method does nothing.
Hook to allow derived classes to override behavior associated with extracting params from a GString.
gstring - a GString containing the SQL query with embedded paramsGets the resultSetConcurrency for statements created using the connection.
Gets the resultSetHoldability for statements created using the connection.
Gets the resultSetType for statements created using the connection.
Create an inout parameter using this in parameter.
in - the InParameter of interestCaches the connection used while the closure is active. If the closure takes a single argument, it will be called with the connection, otherwise it will be called with no arguments.
closure - the given closureReturns true if the current Sql object is currently executing a withBatch method call.
Attempts to load the JDBC driver on the thread, current or system class loaders
driverClassName - the fully qualified class name of the driver classCreates a new Sql instance given a JDBC connection URL.
url - a database url of the form
jdbc:subprotocol:subnameCreates a new Sql instance given a JDBC connection URL and some properties.
url - a database url of the form
jdbc:subprotocol:subnameproperties - a list of arbitrary string tag/value pairs
as connection arguments; normally at least a "user" and
"password" property should be includedCreates a new Sql instance given a JDBC connection URL, some properties and a driver class name.
url - a database url of the form
jdbc:subprotocol:subnameproperties - a list of arbitrary string tag/value pairs
as connection arguments; normally at least a "user" and
"password" property should be includeddriverClassName - the fully qualified class name of the driver classCreates a new Sql instance given a JDBC connection URL, a username and a password.
url - a database url of the form
jdbc:subprotocol:subnameuser - the database user on whose behalf the connection
is being madepassword - the user's passwordCreates a new Sql instance given a JDBC connection URL, a username, a password and a driver class name.
url - a database url of the form
jdbc:subprotocol:subnameuser - the database user on whose behalf the connection
is being madepassword - the user's passworddriverClassName - the fully qualified class name of the driver classCreates a new Sql instance given a JDBC connection URL and a driver class name.
url - a database url of the form
jdbc:subprotocol:subnamedriverClassName - the fully qualified class name of the driver classCreates a new Sql instance given parameters in a Map. Recognized keys for the Map include:
driverClassName the fully qualified class name of the driver class
driver a synonym for driverClassName
url a database url of the form: jdbc:subprotocol:subname
user the database user on whose behalf the connection is being made
password the user's password
properties a list of arbitrary string tag/value pairs as connection arguments;
normally at least a "user" and "password" property should be included
other any of the public setter methods of this class may be used with property notation
e.g. cacheStatements: true, resultSetConcurrency: ResultSet.CONCUR_READ_ONLY
Of these, 'url' is required. Others may be needed depending on your database.properties' is supplied, neither 'user' nor 'password' should be supplied.user' or 'password' is supplied, both should be supplied.
Example usage:
import groovy.sql.Sql
import static java.sql.ResultSet.*
def sql = Sql.newInstance(
url:'jdbc:hsqldb:mem:testDB',
user:'sa',
password:'',
driver:'org.hsqldb.jdbc.JDBCDriver',
cacheStatements: true,
resultSetConcurrency: CONCUR_READ_ONLY
)
args - a Map contain further argumentsHook to allow derived classes to override null handling. Default behavior is to replace ?'"? references with NULLish
sql - the SQL statementCreate a new OutParameter
type - the JDBC data type. Performs the given SQL query, which should return a single
ResultSet object. The given closure is called
with the ResultSet as its argument.
The query may contain placeholder question marks which match the given list of parameters.
Example usage:
sql.query('select * from PERSON where lastname like ?', ['%a%']) { ResultSet rs ->
while (rs.next()) println rs.getString('lastname')
}
This method supports named and named ordinal parameters. See the class Javadoc for more details.
All resources including the ResultSet are closed automatically after the closure is called.
sql - the sql statementparams - a list of parametersclosure - called for each row with a GroovyResultSetA variant of query(String, java.util.List, groovy.lang.Closure) useful when providing the named parameters as a map.
sql - the sql statementmap - a map containing the named parametersclosure - called for each row with a GroovyResultSetCreate a new ResultSetOutParameter
type - the JDBC data type.If this SQL object was created with a Connection then this method rolls back the connection. If this SQL object was created from a DataSource then this method does nothing.
Performs the given SQL query and return the rows of the result set. The query may contain placeholder question marks which match the given list of parameters.
Example usage:
def ans = sql.rows("select * from PERSON where lastname like ?", ['%a%'])
println "Found ${ans.size()} rows"
This method supports named and named ordinal parameters by supplying such
parameters in the params list. See the class Javadoc for more details.
Resource handling is performed automatically where appropriate.
sql - the SQL statementparams - a list of parametersA variant of rows(String, java.util.List, int, int, groovy.lang.Closure) useful when providing the named parameters as a map.
sql - the SQL statementparams - a map of named parametersoffset - the 1-based offset for the first row to be processedmaxRows - the maximum number of rows to be processedmetaClosure - called for meta data (only once after sql execution) Performs the given SQL query and return a "page" of rows from the result set. A page is defined as starting at
a 1-based offset, and containing a maximum number of rows.
In addition, the metaClosure will be called once passing in the
ResultSetMetaData as argument.
The query may contain GString expressions.
Note that the underlying implementation is based on either invoking ResultSet.absolute(),
or if the ResultSet type is ResultSet.TYPE_FORWARD_ONLY, the ResultSet.next() method
is invoked equivalently. The first row of a ResultSet is 1, so passing in an offset of 1 or less has no effect
on the initial positioning within the result set.
Note that different database and JDBC driver implementations may work differently with respect to this method.
Specifically, one should expect that ResultSet.TYPE_FORWARD_ONLY may be less efficient than a
"scrollable" type.
Resource handling is performed automatically where appropriate.
gstring - the SQL statementoffset - the 1-based offset for the first row to be processedmaxRows - the maximum number of rows to be processedmetaClosure - called for meta data (only once after sql execution)
Strategy method allowing derived classes to handle types differently such as for CLOBs etc.
statement - the statement of interesti - the index of the object of interestvalue - the new object valueSets the resultSetConcurrency for statements created using the connection. May cause SQLFeatureNotSupportedException exceptions to occur if the underlying database doesn't support the requested concurrency value.
resultSetConcurrency - one of the following ResultSet
constants:
ResultSet.CONCUR_READ_ONLY or
ResultSet.CONCUR_UPDATABLESets the resultSetHoldability for statements created using the connection. May cause SQLFeatureNotSupportedException exceptions to occur if the underlying database doesn't support the requested holdability value.
resultSetHoldability - one of the following ResultSet
constants:
ResultSet.HOLD_CURSORS_OVER_COMMIT or
ResultSet.CLOSE_CURSORS_AT_COMMITSets the resultSetType for statements created using the connection. May cause SQLFeatureNotSupportedException exceptions to occur if the underlying database doesn't support the requested type value.
resultSetType - one of the following ResultSet
constants:
ResultSet.TYPE_FORWARD_ONLY,
ResultSet.TYPE_SCROLL_INSENSITIVE, or
ResultSet.TYPE_SCROLL_SENSITIVEPerforms the closure (containing batch operations specific to an associated prepared statement) within a batch. Uses a batch size of zero, i.e. no automatic partitioning of batches.
This means that executeBatch() will be called automatically after the withBatch
closure has finished but may be called explicitly if desired as well for more fine-grained
partitioning of the batch.
The closure will be called with a single argument; the prepared
statement (actually a BatchingPreparedStatementWrapper helper object)
associated with this batch.
An example:
def updateCounts = sql.withBatch('insert into TABLENAME(a, b, c) values (?, ?, ?)') { ps ->
ps.addBatch([10, 12, 5])
ps.addBatch([7, 3, 98])
ps.addBatch(22, 67, 11)
def partialUpdateCounts = ps.executeBatch() // optional interim batching
ps.addBatch(30, 40, 50)
...
}
For integrity and performance reasons, you may wish to consider executing your batch command(s) within a transaction:
sql.withTransaction {
def result1 = sql.withBatch { ... }
...
}
Statement, or the
driver does not support batch statements. Throws BatchUpdateException
(a subclass of SQLException) if one of the commands sent to the
database fails to execute properly or attempts to return a result set.sql - batch update statementclosure - the closure containing batch statements (to bind parameters) and optionally other statementsInvokes a closure passing it a new Sql instance created from the given JDBC connection URL. The created connection will be closed if required.
url - a database url of the form
jdbc:subprotocol:subnamec - the Closure to callInvokes a closure passing it a new Sql instance created from the given JDBC connection URL and properties. The created connection will be closed if required.
url - a database url of the form
jdbc:subprotocol:subnameproperties - a list of arbitrary string tag/value pairs
as connection arguments; normally at least a "user" and
"password" property should be includedc - the Closure to callInvokes a closure passing it a new Sql instance created from the given JDBC connection URL, properties and driver classname. The created connection will be closed if required.
url - a database url of the form
jdbc:subprotocol:subnameproperties - a list of arbitrary string tag/value pairs
as connection arguments; normally at least a "user" and
"password" property should be includeddriverClassName - the fully qualified class name of the driver classc - the Closure to callInvokes a closure passing it a new Sql instance created from the given JDBC connection URL, user and password. The created connection will be closed if required.
url - a database url of the form
jdbc:subprotocol:subnameuser - the database user on whose behalf the connection
is being madepassword - the user's passwordc - the Closure to callInvokes a closure passing it a new Sql instance created from the given JDBC connection URL. The created connection will be closed if required.
url - a database url of the form
jdbc:subprotocol:subnameuser - the database user on whose behalf the connection
is being madepassword - the user's passworddriverClassName - the fully qualified class name of the driver classc - the Closure to callInvokes a closure passing it a new Sql instance created from the given JDBC connection URL. The created connection will be closed if required.
url - a database url of the form
jdbc:subprotocol:subnamedriverClassName - the fully qualified class name of the driver classc - the Closure to callInvokes a closure passing it a new Sql instance created from the given map of arguments. The created connection will be closed if required.
args - a Map contain further argumentsc - the Closure to call Enables statement caching.
if cacheStatements is true, cache is created and all created prepared statements will be cached.
if cacheStatements is false, all cached statements will be properly closed.
cacheStatements - the new valuePerforms the closure within a transaction using a cached connection. If the closure takes a single argument, it will be called with the connection, otherwise it will be called with no arguments.
closure - the given closureCopyright © 2003-2014 The Codehaus. All rights reserved.