Class Sql
- Direct Known Subclasses:
DataSet
Typical usage
First you need to set up your sql instance. There are several constructors and a fewnewInstance 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.
Avoiding SQL injection
If you find yourself creating queries based on any kind of input from the user or a 3rd party application you might wish to avoid the pure string method variants in this class. While this is safe: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.
Named and named ordinal parameters
Several of the methods in this class (ones which have a String-based sql query and params in a List<Object> or Object[] or Map) support named or named ordinal parameters. These methods are useful for queries with large numbers of parameters - though the GString variations are often preferred in such cases too. Reminder: when you see a variant with Object[] as the type of the last parameter, Groovy allows vararg style parameters so you don't explicitly need to create an Object[] and if the first parameter is of type Map, Groovy supports named arguments - examples of both are contained in the examples below.Named parameter queries use placeholder values in the query String. Two forms are supported ':propname1' and '?.propname2'. For these variations, a single model object is supplied in the parameter list/array/map. The propname refers to a property of that model object. The model object could be a map, Expando or domain class instance. Here are some examples:
// using rows() with a named parameter with the parameter supplied in a map
println sql.rows('select * from PROJECT where name=:foo', [foo:'Gradle'])
// as above for eachRow()
sql.eachRow('select * from PROJECT where name=:foo', [foo:'Gradle']) {
// process row
}
// an example using both the ':' and '?.' variants of the notation
println sql.rows('select * from PROJECT where name=:foo and id=?.bar', [foo:'Gradle', bar:40])
// as above but using Groovy's named arguments instead of an explicit map
println sql.rows('select * from PROJECT where name=:foo and id=?.bar', foo:'Gradle', bar:40)
// an example showing rows() with a domain object instead of a map
class MyDomainClass { def baz = 'Griffon' }
println sql.rows('select * from PROJECT where name=?.baz', new MyDomainClass())
// as above for eachRow() with the domain object supplied in a list
sql.eachRow('select * from PROJECT where name=?.baz', [new MyDomainClass()]) {
// process row
}
Named ordinal parameter queries have multiple model objects with the index number (starting
at 1) also supplied in the placeholder. Only the question mark variation of placeholder is supported.
Here are some examples:
// an example showing the model objects as vararg style parameters (since rows() has an Object[] variant)
println sql.rows("select * from PROJECT where name=?1.baz and id=?2.num", new MyDomainClass(), [num:30])
// an example showing the model objects (one domain class and one map) provided in a list
sql.eachRow("select * from PROJECT where name=?1.baz and id=?2.num", [new MyDomainClass(), [num:30]]) {
// do something with row
}
More details
See the method and constructor JavaDoc for more details.For advanced usage, the class provides numerous extension points for overriding the facade behavior associated with the various aspects of managing the interaction with the underlying database.
- Author:
- Chris Stevenson, James Strachan, Paul King, Marc DeXeT, John Bito, John Hurst, David Durham, Daniel Henrique Alves Lima, David Sutherland
-
Nested Class Summary
Nested Classes -
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final intstatic final OutParameterstatic final OutParameterstatic final OutParameterstatic final OutParameterstatic final OutParameterstatic final OutParameterstatic final OutParameterstatic final OutParameterstatic final OutParameterstatic final OutParameterstatic final OutParameterstatic final OutParameterstatic final OutParameterstatic final intstatic final OutParameterstatic final OutParameterstatic final OutParameterprotected static final LoggerHook to allow derived classes to access the logstatic final OutParameterstatic final OutParameterstatic final intstatic final OutParameterstatic final OutParameterstatic final OutParameterstatic final OutParameterstatic final OutParameterstatic final OutParameterstatic final OutParameterstatic final OutParameterstatic final OutParameterstatic final OutParameterstatic final OutParameterstatic final OutParameter -
Constructor Summary
ConstructorsConstructorDescriptionSql(Connection connection) Constructs an SQL instance using the given Connection.Sql(DataSource dataSource) Constructs an SQL instance using the given DataSource. -
Method Summary
Modifier and TypeMethodDescriptionstatic InParameterprotected List<GroovyRowResult>Hook to allow derived classes to override list of result collection behavior.protected List<GroovyRowResult>protected List<GroovyRowResult>Hook to allow derived classes to override list of result collection behavior.protected StringHook to allow derived classes to override sql generation from GStrings.static InParameterstatic InParameterstatic InParameterstatic InParameterstatic InParameterprotected SqlWithParamsHook to allow derived classes to override behavior associated with the parsing and indexing of parameters from a given sql statement.voidcacheConnection(Closure closure) Caches the connection used while the closure is active.voidcacheStatements(Closure closure) Caches every created preparedStatement in Closure closure Every cached preparedStatement is closed after closure has been called.intPerforms a stored procedure call with the given embedded parameters.voidPerforms a stored procedure call with the given parameters, calling the closure once with all result objects.intPerforms a stored procedure call.intPerforms a stored procedure call with the given parameters.intPerforms a stored procedure call with the given parameters.voidPerforms a stored procedure call with the given parameters.callWithAllRows(GString gstring, Closure closure) Performs a stored procedure call with the given parameters, calling the closure once with all result objects, and also returning a list of lists with the rows of the ResultSet(s).callWithAllRows(String sql, List<Object> params, Closure closure) Performs a stored procedure call with the given parameters, calling the closure once with all result objects, and also returning a list of lists with the rows of the ResultSet(s).callWithRows(GString gstring, Closure closure) Performs a stored procedure call with the given parameters, calling the closure once with all result objects, and also returning the rows of the ResultSet.protected List<List<GroovyRowResult>>callWithRows(String sql, List<Object> params, int processResultsSets, Closure closure) Base internal method for call(), callWithRows(), and callWithAllRows() style of methods.callWithRows(String sql, List<Object> params, Closure closure) Performs a stored procedure call with the given parameters, calling the closure once with all result objects, and also returning the rows of the ResultSet.static InParametercheckForNamedParams(String sql, List<Object> params) static InParametervoidclose()If this SQL object was created with a Connection then this method closes the connection.protected voidcloseResources(Connection connection) An extension point allowing the behavior of resource closing to be overridden in derived classes.protected voidcloseResources(Connection connection, Statement statement) An extension point allowing the behavior of resource closing to be overridden in derived classes.protected voidcloseResources(Connection connection, Statement statement, ResultSet results) An extension point allowing derived classes to change the behavior of resource closing.voidcommit()If this SQL object was created with a Connection then this method commits the connection.protected voidProvides a hook for derived classes to be able to configure JDBC statements.protected ConnectionAn extension point allowing derived classes to change the behavior of connection creation.protected Sql.AbstractQueryCommandcreatePreparedQueryCommand(String sql, List<Object> queryParams) Factory for the PreparedQueryCommand command pattern object allows subclass to supply implementations of the command class.protected Sql.AbstractQueryCommandcreateQueryCommand(String sql) Factory for the QueryCommand command pattern object allows subclasses to supply implementations of the command class.static InParameterstatic InParameterstatic InParameterstatic InParameterstatic InParametervoidPerforms the given SQL query calling the givenclosurewith each row of the result set starting at the providedoffset, and including up tomaxRowsnumber of rows.voidPerforms the given SQL query calling the given Closure with each row of the result set.voidPerforms the given SQL query calling the givenclosurewith each row of the result set starting at the providedoffset, and including up tomaxRowsnumber of rows.voidPerforms the given SQL query calling the given Closure with each row of the result set.voidPerforms the given SQL query calling the givenclosurewith each row of the result set starting at the providedoffset, and including up tomaxRowsnumber of rows.voidPerforms the given SQL query calling the given Closure with each row of the result set.voidPerforms the given SQL query calling the givenrowClosurewith each row of the result set starting at the providedoffset, and including up tomaxRowsnumber of rows.voidPerforms the given SQL query calling the givenrowClosurewith each row of the result set.voidPerforms the given SQL query calling the givenclosurewith each row of the result set starting at the providedoffset, and including up tomaxRowsnumber of rows.voidPerforms the given SQL query calling the given Closure with each row of the result set.voideachRow(String sql, List<Object> params, Closure metaClosure, int offset, int maxRows, Closure rowClosure) Performs the given SQL query calling the givenrowClosurewith each row of the result set starting at the providedoffset, and including up tomaxRowsnumber of rows.voidPerforms the given SQL query calling the given Closure with each row of the result set.voidA variant ofeachRow(String, java.util.List, int, int, groovy.lang.Closure)useful when providing the named parameters as a map.voidA variant ofeachRow(String, java.util.List, groovy.lang.Closure)useful when providing the named parameters as a map.voidA variant ofeachRow(String, java.util.List, groovy.lang.Closure, int, int, groovy.lang.Closure)allowing the named parameters to be supplied in a map.voidA variant ofeachRow(String, java.util.List, groovy.lang.Closure, groovy.lang.Closure)useful when providing the named parameters as a map.voidA variant ofeachRow(String, java.util.List, int, int, groovy.lang.Closure)useful when providing the named parameters as named arguments.voidA variant ofeachRow(String, java.util.List, groovy.lang.Closure)useful when providing the named parameters as named arguments.voidA variant ofeachRow(String, java.util.List, groovy.lang.Closure, int, int, groovy.lang.Closure)allowing the named parameters to be supplied as named arguments.voidA variant ofeachRow(String, java.util.List, groovy.lang.Closure, groovy.lang.Closure)useful when providing the named parameters as named arguments.booleanExecutes the given SQL with embedded expressions inside.voidExecutes the given SQL with embedded expressions inside.booleanExecutes the given piece of SQL.voidExecutes the given piece of SQL.booleanExecutes the given piece of SQL with parameters.voidExecutes the given piece of SQL with parameters.booleanExecutes the given piece of SQL with parameters.voidExecutes the given piece of SQL with parameters.booleanA variant ofexecute(String, java.util.List)useful when providing the named parameters as named arguments.voidA variant ofexecute(String, java.util.List, Closure)useful when providing the named parameters as named arguments.executeInsert(GString gstring) Executes the given SQL statement (typically an INSERT statement).executeInsert(GString gstring, List<String> keyColumnNames) Executes the given SQL statement (typically an INSERT statement).executeInsert(String sql) Executes the given SQL statement (typically an INSERT statement).executeInsert(String sql, Object[] params) Executes the given SQL statement (typically an INSERT statement).executeInsert(String sql, String[] keyColumnNames) Executes the given SQL statement (typically an INSERT statement).executeInsert(String sql, String[] keyColumnNames, Object[] params) Executes the given SQL statement (typically an INSERT statement).executeInsert(String sql, List<Object> params) Executes the given SQL statement (typically an INSERT statement).Executes the given SQL statement (typically an INSERT statement).executeInsert(Map params, String sql) A variant ofexecuteInsert(String, java.util.List)useful when providing the named parameters as named arguments.executeInsert(Map params, String sql, List<String> keyColumnNames) A variant ofexecuteInsert(String, List, List)useful when providing the named parameters as named arguments.protected final ResultSetexecutePreparedQuery(String sql, List<Object> params) Useful helper method which handles resource management when executing a prepared query which returns a result set.protected final ResultSetexecuteQuery(String sql) Useful helper method which handles resource management when executing a query which returns a result set.intexecuteUpdate(GString gstring) Executes the given SQL update with embedded expressions inside.intexecuteUpdate(String sql) Executes the given SQL update.intexecuteUpdate(String sql, Object[] params) Executes the given SQL update with parameters.intexecuteUpdate(String sql, List<Object> params) Executes the given SQL update with parameters.intexecuteUpdate(Map params, String sql) A variant ofexecuteUpdate(String, java.util.List)useful when providing the named parameters as named arguments.static ExpandedVariableWhen using GString SQL queries, allows a variable to be expanded in the Sql string rather than representing an sql parameter.protected intfindWhereKeyword(String sql) Hook to allow derived classes to override where clause sniffing.Performs the given SQL query and return the first row of the result set.Performs the given SQL query and return the first row of the result set.Performs the given SQL query and return the first row of the result set.Performs the given SQL query and return the first row of the result set.A variant offirstRow(String, java.util.List)useful when providing the named parameters as named arguments.static InParameterIf this instance was created with a single Connection then the connection is returned.getParameters(GString gstring) Hook to allow derived classes to override behavior associated with extracting params from a GString.intGets the resultSetConcurrency for statements created using the connection.intGets the resultSetHoldability for statements created using the connection.intGets the resultSetType for statements created using the connection.intgetUpdatedParams(List<Object> params, List<Tuple> indexPropList) static InParameterCreate a new InParameterstatic InOutParameterinout(InParameter in) Create an inout parameter using this in parameter.static InParameterbooleanbooleanbooleanbooleanbooleanReturns true if the current Sql object is currently executing a withBatch method call.static InParameterJAVA_OBJECT(Object value) static voidloadDriver(String driverClassName) Attempts to load the JDBC driver on the thread, current or system class loadersstatic InParameterLONGVARBINARY(Object value) static InParameterLONGVARCHAR(Object value) static SqlnewInstance(String url) Creates a new Sql instance given a JDBC connection URL.static SqlnewInstance(String url, String driverClassName) Creates a new Sql instance given a JDBC connection URL and a driver class name.static SqlnewInstance(String url, String user, String password) Creates a new Sql instance given a JDBC connection URL, a username and a password.static SqlnewInstance(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 SqlnewInstance(String url, Properties properties) Creates a new Sql instance given a JDBC connection URL and some properties.static SqlnewInstance(String url, Properties properties, String driverClassName) Creates a new Sql instance given a JDBC connection URL, some properties and a driver class name.static SqlnewInstance(Map<String, Object> args) Creates a new Sql instance given parameters in a Map.static InParameterprotected StringHook to allow derived classes to override null handling.static InParameterstatic InParameterstatic OutParameterout(int type) Create a new OutParameterDeprecated.voidPerforms the given SQL query, which should return a singleResultSetobject.voidPerforms the given SQL query, which should return a singleResultSetobject.voidPerforms the given SQL query, which should return a singleResultSetobject.voidA variant ofquery(String, java.util.List, groovy.lang.Closure)useful when providing the named parameters as a map.voidA variant ofquery(String, java.util.List, groovy.lang.Closure)useful when providing the named parameters as named arguments.static InParameterstatic InParameterstatic ResultSetOutParameterresultSet(int type) Create a new ResultSetOutParametervoidrollback()If this SQL object was created with a Connection then this method rolls back the connection.Performs the given SQL query and return the rows of the result set.Performs the given SQL query and return a "page" of rows from the result set.Performs the given SQL query and return a "page" of rows from the result set.Performs the given SQL query and return the rows of the result set.Performs the given SQL query and return the rows of the result set.Performs the given SQL query and return a "page" of rows from the result set.Performs the given SQL query and return a "page" of rows from the result set.Performs the given SQL query and return the rows of the result set.Performs the given SQL query and return the rows of the result set.Performs the given SQL query and return the rows of the result set.Performs the given SQL query and return the rows of the result set.Performs the given SQL query and return a "page" of rows from the result set.Performs the given SQL query and return a "page" of rows from the result set.Performs the given SQL query and return the rows of the result set.A variant ofrows(String, java.util.List, int, int)useful when providing the named parameters as a map.A variant ofrows(String, java.util.List, int, int, groovy.lang.Closure)useful when providing the named parameters as a map.A variant ofrows(String, java.util.List, groovy.lang.Closure)useful when providing the named parameters as a map.A variant ofrows(String, java.util.List)useful when providing the named parameters as named arguments.A variant ofrows(String, java.util.List, int, int)useful when providing the named parameters as named arguments.A variant ofrows(String, java.util.List, int, int, groovy.lang.Closure)useful when providing the named parameters as named arguments.A variant ofrows(String, java.util.List, groovy.lang.Closure)useful when providing the named parameters as named arguments.voidsetCacheNamedQueries(boolean cacheNamedQueries) Enables named query caching.
if cacheNamedQueries is true, cache is created and processed named queries will be cached.voidsetCacheStatements(boolean cacheStatements) Enables statement caching.
if cacheStatements is true, cache is created and all created prepared statements will be cached.voidsetEnableMetaDataChecking(boolean enableMetaDataChecking) voidsetEnableNamedQueries(boolean enableNamedQueries) Enables named query support: if enableNamedQueries is true, queries with ':propname' and '?1.propname' style placeholders will be processed. if enableNamedQueries is false, this feature will be turned off.protected voidStub needed for testing.protected voidsetObject(PreparedStatement statement, int i, Object value) Strategy method allowing derived classes to handle types differently such as for CLOBs etc.protected voidsetParameters(List<Object> params, PreparedStatement statement) Hook to allow derived classes to override behavior associated with setting params for a prepared statement.voidsetResultSetConcurrency(int resultSetConcurrency) Sets the resultSetConcurrency for statements created using the connection.voidsetResultSetHoldability(int resultSetHoldability) Sets the resultSetHoldability for statements created using the connection.voidsetResultSetType(int resultSetType) Sets the resultSetType for statements created using the connection.static InParameterstatic InParameterstatic InParameterstatic InParameterstatic InParameterstatic InParameterstatic InParameterint[]Performs the closure (containing batch operations) within a batch using a given batch size.int[]Performs the closure (containing batch operations specific to an associated prepared statement) within a batch using a given batch size.int[]Performs the closure (containing batch operations) within a batch.int[]Performs the closure (containing batch operations specific to an associated prepared statement) within a batch.static voidwithInstance(String url, Closure c) Invokes a closure passing it a new Sql instance created from the given JDBC connection URL.static voidwithInstance(String url, String driverClassName, Closure c) Invokes a closure passing it a new Sql instance created from the given JDBC connection URL.static voidwithInstance(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 voidInvokes a closure passing it a new Sql instance created from the given JDBC connection URL.static voidwithInstance(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 voidwithInstance(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 voidwithInstance(Map<String, Object> args, Closure c) Invokes a closure passing it a new Sql instance created from the given map of arguments.voidwithStatement(Closure configureStatement) Allows a closure to be passed in to configure the JDBC statements before they are executed.voidwithTransaction(Closure closure) Performs the closure within a transaction using a cached connection.
-
Field Details
-
LOG
Hook to allow derived classes to access the log -
ARRAY
-
BIGINT
-
BINARY
-
BIT
-
BLOB
-
BOOLEAN
-
CHAR
-
CLOB
-
DATALINK
-
DATE
-
DECIMAL
-
DISTINCT
-
DOUBLE
-
FLOAT
-
INTEGER
-
JAVA_OBJECT
-
LONGVARBINARY
-
LONGVARCHAR
-
NULL
-
NUMERIC
-
OTHER
-
REAL
-
REF
-
SMALLINT
-
STRUCT
-
TIME
-
TIMESTAMP
-
TINYINT
-
VARBINARY
-
VARCHAR
-
NO_RESULT_SETS
public static final int NO_RESULT_SETS- See Also:
-
FIRST_RESULT_SET
public static final int FIRST_RESULT_SET- See Also:
-
ALL_RESULT_SETS
public static final int ALL_RESULT_SETS- See Also:
-
-
Constructor Details
-
Sql
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.- Parameters:
dataSource- the DataSource to use
-
Sql
Constructs an SQL instance using the given Connection. It is the caller's responsibility to close the Connection after the Sql instance has been used. Depending on which features you are using, you may be able to do this on the connection object directly but the preferred approach is to call theclose()method which will close the connection but also free any caches resources.- Parameters:
connection- the Connection to use
-
Sql
-
-
Method Details
-
isEnableMetaDataChecking
public boolean isEnableMetaDataChecking() -
setEnableMetaDataChecking
public void setEnableMetaDataChecking(boolean enableMetaDataChecking) -
newInstance
Creates a new Sql instance given a JDBC connection URL.- Parameters:
url- a database url of the formjdbc:subprotocol:subname- Returns:
- a new Sql instance with a connection
- Throws:
SQLException- if a database access error occurs
-
withInstance
Invokes a closure passing it a new Sql instance created from the given JDBC connection URL. The created connection will be closed if required.- Parameters:
url- a database url of the formjdbc:subprotocol:subnamec- the Closure to call- Throws:
SQLException- if a database access error occurs- See Also:
-
newInstance
Creates a new Sql instance given a JDBC connection URL and some properties.- Parameters:
url- a database url of the formjdbc:subprotocol:subnameproperties- a list of arbitrary string tag/value pairs as connection arguments; normally at least a "user" and "password" property should be included- Returns:
- a new Sql instance with a connection
- Throws:
SQLException- if a database access error occurs
-
withInstance
Invokes 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.- Parameters:
url- a database url of the formjdbc: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 call- Throws:
SQLException- if a database access error occurs- See Also:
-
newInstance
public static Sql newInstance(String url, Properties properties, String driverClassName) throws SQLException, ClassNotFoundException Creates a new Sql instance given a JDBC connection URL, some properties and a driver class name.- Parameters:
url- a database url of the formjdbc: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 class- Returns:
- a new Sql instance with a connection
- Throws:
SQLException- if a database access error occursClassNotFoundException- if the driver class cannot be found or loaded
-
withInstance
public static void withInstance(String url, Properties properties, String driverClassName, Closure c) throws SQLException, ClassNotFoundException Invokes 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.- Parameters:
url- a database url of the formjdbc: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 call- Throws:
SQLException- if a database access error occursClassNotFoundException- if the driver class cannot be found or loaded- See Also:
-
newInstance
Creates a new Sql instance given a JDBC connection URL, a username and a password.- Parameters:
url- a database url of the formjdbc:subprotocol:subnameuser- the database user on whose behalf the connection is being madepassword- the user's password- Returns:
- a new Sql instance with a connection
- Throws:
SQLException- if a database access error occurs
-
withInstance
public static void withInstance(String url, String user, String password, Closure c) throws SQLException Invokes 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.- Parameters:
url- a database url of the formjdbc:subprotocol:subnameuser- the database user on whose behalf the connection is being madepassword- the user's passwordc- the Closure to call- Throws:
SQLException- if a database access error occurs- See Also:
-
newInstance
public static Sql newInstance(String url, String user, String password, String driverClassName) throws SQLException, ClassNotFoundException Creates a new Sql instance given a JDBC connection URL, a username, a password and a driver class name.- Parameters:
url- a database url of the formjdbc: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 class- Returns:
- a new Sql instance with a connection
- Throws:
SQLException- if a database access error occursClassNotFoundException- if the driver class cannot be found or loaded
-
withInstance
public static void withInstance(String url, String user, String password, String driverClassName, Closure c) throws SQLException, ClassNotFoundException Invokes a closure passing it a new Sql instance created from the given JDBC connection URL. The created connection will be closed if required.- Parameters:
url- a database url of the formjdbc: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 call- Throws:
SQLException- if a database access error occursClassNotFoundException- if the driver class cannot be found or loaded- See Also:
-
newInstance
public static Sql newInstance(String url, String driverClassName) throws SQLException, ClassNotFoundException Creates a new Sql instance given a JDBC connection URL and a driver class name.- Parameters:
url- a database url of the formjdbc:subprotocol:subnamedriverClassName- the fully qualified class name of the driver class- Returns:
- a new Sql instance with a connection
- Throws:
SQLException- if a database access error occursClassNotFoundException- if the driver class cannot be found or loaded
-
withInstance
public static void withInstance(String url, String driverClassName, Closure c) throws SQLException, ClassNotFoundException Invokes a closure passing it a new Sql instance created from the given JDBC connection URL. The created connection will be closed if required.- Parameters:
url- a database url of the formjdbc:subprotocol:subnamedriverClassName- the fully qualified class name of the driver classc- the Closure to call- Throws:
SQLException- if a database access error occursClassNotFoundException- if the driver class cannot be found or loaded- See Also:
-
newInstance
Creates 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:
Of these, 'jdbc:subprotocol:subnameuser 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_ONLYurl' is required. Others may be needed depending on your database.
If 'properties' is supplied, neither 'user' nor 'password' should be supplied.
If one of '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 )- Parameters:
args- a Map contain further arguments- Returns:
- a new Sql instance with a connection
- Throws:
SQLException- if a database access error occursClassNotFoundException- if the driver class cannot be found or loaded
-
withInstance
public static void withInstance(Map<String, Object> args, Closure c) throws SQLException, ClassNotFoundExceptionInvokes a closure passing it a new Sql instance created from the given map of arguments. The created connection will be closed if required.- Parameters:
args- a Map contain further argumentsc- the Closure to call- Throws:
SQLException- if a database access error occursClassNotFoundException- if the driver class cannot be found or loaded- See Also:
-
getResultSetType
public int getResultSetType()Gets the resultSetType for statements created using the connection.- Returns:
- the current resultSetType value
- Since:
- 1.5.2
-
setResultSetType
public void setResultSetType(int resultSetType) Sets 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.- Parameters:
resultSetType- one of the followingResultSetconstants:ResultSet.TYPE_FORWARD_ONLY,ResultSet.TYPE_SCROLL_INSENSITIVE, orResultSet.TYPE_SCROLL_SENSITIVE- Since:
- 1.5.2
-
getResultSetConcurrency
public int getResultSetConcurrency()Gets the resultSetConcurrency for statements created using the connection.- Returns:
- the current resultSetConcurrency value
- Since:
- 1.5.2
-
setResultSetConcurrency
public void setResultSetConcurrency(int resultSetConcurrency) Sets 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.- Parameters:
resultSetConcurrency- one of the followingResultSetconstants:ResultSet.CONCUR_READ_ONLYorResultSet.CONCUR_UPDATABLE- Since:
- 1.5.2
-
getResultSetHoldability
public int getResultSetHoldability()Gets the resultSetHoldability for statements created using the connection.- Returns:
- the current resultSetHoldability value or -1 if not set
- Since:
- 1.5.2
-
setResultSetHoldability
public void setResultSetHoldability(int resultSetHoldability) Sets 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.- Parameters:
resultSetHoldability- one of the followingResultSetconstants:ResultSet.HOLD_CURSORS_OVER_COMMITorResultSet.CLOSE_CURSORS_AT_COMMIT- Since:
- 1.5.2
-
loadDriver
Attempts to load the JDBC driver on the thread, current or system class loaders- Parameters:
driverClassName- the fully qualified class name of the driver class- Throws:
ClassNotFoundException- if the class cannot be found or loaded
-
ARRAY
-
BIGINT
-
BINARY
-
BIT
-
BLOB
-
BOOLEAN
-
CHAR
-
CLOB
-
DATALINK
-
DATE
-
DECIMAL
-
DISTINCT
-
DOUBLE
-
FLOAT
-
INTEGER
-
JAVA_OBJECT
-
LONGVARBINARY
-
LONGVARCHAR
-
NULL
-
NUMERIC
-
OTHER
-
REAL
-
REF
-
SMALLINT
-
STRUCT
-
TIME
-
TIMESTAMP
-
TINYINT
-
VARBINARY
-
VARCHAR
-
in
Create a new InParameter- Parameters:
type- the JDBC data typevalue- the object value- Returns:
- an InParameter
-
out
Create a new OutParameter- Parameters:
type- the JDBC data type.- Returns:
- an OutParameter
-
inout
Create an inout parameter using this in parameter.- Parameters:
in- the InParameter of interest- Returns:
- the resulting InOutParameter
-
resultSet
Create a new ResultSetOutParameter- Parameters:
type- the JDBC data type.- Returns:
- a ResultSetOutParameter
-
expand
When 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]- Parameters:
object- the object of interest- Returns:
- the expanded variable
- See Also:
-
dataSet
-
dataSet
-
query
Performs the given SQL query, which should return a singleResultSetobject. The given closure is called with theResultSetas its argument.Example usages:
sql.query("select * from PERSON where firstname like 'S%'") { ResultSet rs -> while (rs.next()) println rs.getString('firstname') + ' ' + rs.getString(3) } sql.query("call get_people_places()") { ResultSet rs -> while (rs.next()) println rs.toRowResult().firstname }All resources including the ResultSet are closed automatically after the closure is called.
- Parameters:
sql- the sql statementclosure- called for each row with aResultSet- Throws:
SQLException- if a database access error occurs
-
query
Performs the given SQL query, which should return a singleResultSetobject. The given closure is called with theResultSetas 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.
- Parameters:
sql- the sql statementparams- a list of parametersclosure- called for each row with aResultSet- Throws:
SQLException- if a database access error occurs
-
query
A variant ofquery(String, java.util.List, groovy.lang.Closure)useful when providing the named parameters as a map.- Parameters:
sql- the sql statementmap- a map containing the named parametersclosure- called for each row with aResultSet- Throws:
SQLException- if a database access error occurs- Since:
- 1.8.7
-
query
A variant ofquery(String, java.util.List, groovy.lang.Closure)useful when providing the named parameters as named arguments.- Parameters:
map- a map containing the named parameterssql- the sql statementclosure- called for each row with aResultSet- Throws:
SQLException- if a database access error occurs- Since:
- 1.8.7
-
query
Performs the given SQL query, which should return a singleResultSetobject. The given closure is called with theResultSetas its argument. The query may contain GString expressions.Example usage:
def location = 25 sql.query "select * from PERSON where location_id < $location", { ResultSet rs -> while (rs.next()) println rs.getString('firstname') }All resources including the ResultSet are closed automatically after the closure is called.
- Parameters:
gstring- a GString containing the SQL query with embedded paramsclosure- called for each row with aResultSet- Throws:
SQLException- if a database access error occurs- See Also:
-
eachRow
Performs the given SQL query calling the given Closure with each row of the result set. The row will be aGroovyResultSetwhich is aResultSetthat supports accessing the fields using property style notation and ordinal index values.Example usages:
sql.eachRow("select * from PERSON where firstname like 'S%'") { row -> println "$row.firstname ${row[2]}}" } sql.eachRow "call my_stored_proc_returning_resultset()", { println it.firstname }Resource handling is performed automatically where appropriate.
- Parameters:
sql- the sql statementclosure- called for each row with a GroovyResultSet- Throws:
SQLException- if a database access error occurs
-
eachRow
Performs the given SQL query calling the givenclosurewith each row of the result set starting at the providedoffset, and including up tomaxRowsnumber of rows. The row will be aGroovyResultSetwhich is aResultSetthat supports accessing the fields using property style notation and ordinal index values.Note that the underlying implementation is based on either invoking
ResultSet.absolute(), or if the ResultSet type isResultSet.TYPE_FORWARD_ONLY, theResultSet.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_ONLYmay be less efficient than a "scrollable" type.Resource handling is performed automatically where appropriate.
- Parameters:
sql- the sql statementoffset- the 1-based offset for the first row to be processedmaxRows- the maximum number of rows to be processedclosure- called for each row with a GroovyResultSet- Throws:
SQLException- if a database access error occurs
-
eachRow
Performs the given SQL query calling the givenrowClosurewith each row of the result set. The row will be aGroovyResultSetwhich is aResultSetthat supports accessing the fields using property style notation and ordinal index values. In addition, themetaClosurewill be called once passing in theResultSetMetaDataas argument.Example usage:
def printColNames = { meta -> (1..meta.columnCount).each { print meta.getColumnLabel(it).padRight(20) } println() } def printRow = { row -> row.toRowResult().values().each{ print it.toString().padRight(20) } println() } sql.eachRow("select * from PERSON", printColNames, printRow)Resource handling is performed automatically where appropriate.
- Parameters:
sql- the sql statementmetaClosure- called for meta data (only once after sql execution)rowClosure- called for each row with a GroovyResultSet- Throws:
SQLException- if a database access error occurs
-
eachRow
public void eachRow(String sql, Closure metaClosure, int offset, int maxRows, Closure rowClosure) throws SQLException Performs the given SQL query calling the givenrowClosurewith each row of the result set starting at the providedoffset, and including up tomaxRowsnumber of rows. The row will be aGroovyResultSetwhich is aResultSetthat supports accessing the fields using property style notation and ordinal index values.In addition, the
metaClosurewill be called once passing in theResultSetMetaDataas argument.Note that the underlying implementation is based on either invoking
ResultSet.absolute(), or if the ResultSet type isResultSet.TYPE_FORWARD_ONLY, theResultSet.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_ONLYmay be less efficient than a "scrollable" type.Resource handling is performed automatically where appropriate.
- Parameters:
sql- 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)rowClosure- called for each row with a GroovyResultSet- Throws:
SQLException- if a database access error occurs
-
eachRow
public void eachRow(String sql, List<Object> params, Closure metaClosure, int offset, int maxRows, Closure rowClosure) throws SQLException Performs the given SQL query calling the givenrowClosurewith each row of the result set starting at the providedoffset, and including up tomaxRowsnumber of rows. The row will be aGroovyResultSetwhich is aResultSetthat supports accessing the fields using property style notation and ordinal index values.In addition, the
metaClosurewill be called once passing in theResultSetMetaDataas 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 isResultSet.TYPE_FORWARD_ONLY, theResultSet.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_ONLYmay be less efficient than a "scrollable" type.- Parameters:
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 GroovyResultSet- Throws:
SQLException- if a database access error occurs
-
eachRow
public void eachRow(String sql, Map map, Closure metaClosure, int offset, int maxRows, Closure rowClosure) throws SQLException A variant ofeachRow(String, java.util.List, groovy.lang.Closure, int, int, groovy.lang.Closure)allowing the named parameters to be supplied in a map.- Parameters:
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 GroovyResultSet- Throws:
SQLException- if a database access error occurs- Since:
- 1.8.7
-
eachRow
public void eachRow(Map map, String sql, Closure metaClosure, int offset, int maxRows, Closure rowClosure) throws SQLException A variant ofeachRow(String, java.util.List, groovy.lang.Closure, int, int, groovy.lang.Closure)allowing the named parameters to be supplied as named arguments.- Parameters:
map- a map containing the named parameterssql- 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)rowClosure- called for each row with a GroovyResultSet- Throws:
SQLException- if a database access error occurs- Since:
- 1.8.7
-
eachRow
public void eachRow(String sql, List<Object> params, Closure metaClosure, Closure rowClosure) throws SQLException Performs the given SQL query calling the given Closure with each row of the result set. The row will be aGroovyResultSetwhich is aResultSetthat supports accessing the fields using property style notation and ordinal index values. In addition, themetaClosurewill be called once passing in theResultSetMetaDataas argument. The query may contain placeholder question marks which match the given list of parameters.Example usage:
def printColNames = { meta -> (1..meta.columnCount).each { print meta.getColumnLabel(it).padRight(20) } println() } def printRow = { row -> row.toRowResult().values().each{ print it.toString().padRight(20) } println() } sql.eachRow("select * from PERSON where lastname like ?", ['%a%'], printColNames, printRow)This method supports named and named ordinal parameters. See the class Javadoc for more details.
Resource handling is performed automatically where appropriate.
- Parameters:
sql- the sql statementparams- a list of parametersmetaClosure- called for meta data (only once after sql execution)rowClosure- called for each row with a GroovyResultSet- Throws:
SQLException- if a database access error occurs
-
eachRow
public void eachRow(String sql, Map params, Closure metaClosure, Closure rowClosure) throws SQLException A variant ofeachRow(String, java.util.List, groovy.lang.Closure, groovy.lang.Closure)useful when providing the named parameters as a map.- Parameters:
sql- the sql statementparams- a map of named parametersmetaClosure- called for meta data (only once after sql execution)rowClosure- called for each row with a GroovyResultSet- Throws:
SQLException- if a database access error occurs- Since:
- 1.8.7
-
eachRow
public void eachRow(Map params, String sql, Closure metaClosure, Closure rowClosure) throws SQLException A variant ofeachRow(String, java.util.List, groovy.lang.Closure, groovy.lang.Closure)useful when providing the named parameters as named arguments.- Parameters:
params- a map of named parameterssql- the sql statementmetaClosure- called for meta data (only once after sql execution)rowClosure- called for each row with a GroovyResultSet- Throws:
SQLException- if a database access error occurs- Since:
- 1.8.7
-
eachRow
Performs the given SQL query calling the given Closure with each row of the result set. The row will be aGroovyResultSetwhich is aResultSetthat supports accessing the fields using property style notation and ordinal index values. The query may contain placeholder question marks which match the given list of parameters.Example usage:
sql.eachRow("select * from PERSON where lastname like ?", ['%a%']) { row -> println "${row[1]} $row.lastname" }Resource handling is performed automatically where appropriate.
- Parameters:
sql- the sql statementparams- a list of parametersclosure- called for each row with a GroovyResultSet- Throws:
SQLException- if a database access error occurs
-
eachRow
A variant ofeachRow(String, java.util.List, groovy.lang.Closure)useful when providing the named parameters as a map.- Parameters:
sql- the sql statementparams- a map of named parametersclosure- called for each row with a GroovyResultSet- Throws:
SQLException- if a database access error occurs- Since:
- 1.8.7
-
eachRow
A variant ofeachRow(String, java.util.List, groovy.lang.Closure)useful when providing the named parameters as named arguments.- Parameters:
params- a map of named parameterssql- the sql statementclosure- called for each row with a GroovyResultSet- Throws:
SQLException- if a database access error occurs- Since:
- 1.8.7
-
eachRow
public void eachRow(String sql, List<Object> params, int offset, int maxRows, Closure closure) throws SQLException Performs the given SQL query calling the givenclosurewith each row of the result set starting at the providedoffset, and including up tomaxRowsnumber of rows. The row will be aGroovyResultSetwhich is aResultSetthat supports accessing the fields using property style notation and ordinal index values. 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 isResultSet.TYPE_FORWARD_ONLY, theResultSet.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_ONLYmay be less efficient than a "scrollable" type.- Parameters:
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 processedclosure- called for each row with a GroovyResultSet- Throws:
SQLException- if a database access error occurs
-
eachRow
public void eachRow(String sql, Map params, int offset, int maxRows, Closure closure) throws SQLException A variant ofeachRow(String, java.util.List, int, int, groovy.lang.Closure)useful when providing the named parameters as a map.- Parameters:
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 processedclosure- called for each row with a GroovyResultSet- Throws:
SQLException- if a database access error occurs- Since:
- 1.8.7
-
eachRow
public void eachRow(Map params, String sql, int offset, int maxRows, Closure closure) throws SQLException A variant ofeachRow(String, java.util.List, int, int, groovy.lang.Closure)useful when providing the named parameters as named arguments.- Parameters:
params- a map of named parameterssql- the sql statementoffset- the 1-based offset for the first row to be processedmaxRows- the maximum number of rows to be processedclosure- called for each row with a GroovyResultSet- Throws:
SQLException- if a database access error occurs- Since:
- 1.8.7
-
eachRow
Performs the given SQL query calling the given Closure with each row of the result set. The row will be aGroovyResultSetwhich is aResultSetthat supports accessing the fields using property style notation and ordinal index values.In addition, the
metaClosurewill be called once passing in theResultSetMetaDataas argument. The query may contain GString expressions.Example usage:
def location = 25 def printColNames = { meta -> (1..meta.columnCount).each { print meta.getColumnLabel(it).padRight(20) } println() } def printRow = { row -> row.toRowResult().values().each{ print it.toString().padRight(20) } println() } sql.eachRow("select * from PERSON where location_id < $location", printColNames, printRow)Resource handling is performed automatically where appropriate.
- Parameters:
gstring- a GString containing the SQL query with embedded paramsmetaClosure- called for meta data (only once after sql execution)rowClosure- called for each row with a GroovyResultSet- Throws:
SQLException- if a database access error occurs- See Also:
-
eachRow
public void eachRow(GString gstring, Closure metaClosure, int offset, int maxRows, Closure rowClosure) throws SQLException Performs the given SQL query calling the givenclosurewith each row of the result set starting at the providedoffset, and including up tomaxRowsnumber of rows. The row will be aGroovyResultSetwhich is aResultSetthat supports accessing the fields using property style notation and ordinal index values. In addition, themetaClosurewill be called once passing in theResultSetMetaDataas argument. The query may contain GString expressions.Note that the underlying implementation is based on either invoking
ResultSet.absolute(), or if the ResultSet type isResultSet.TYPE_FORWARD_ONLY, theResultSet.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_ONLYmay be less efficient than a "scrollable" type.- Parameters:
gstring- a GString containing the SQL query with embedded paramsmetaClosure- called for meta data (only once after sql execution)offset- the 1-based offset for the first row to be processedmaxRows- the maximum number of rows to be processedrowClosure- called for each row with a GroovyResultSet- Throws:
SQLException- if a database access error occurs
-
eachRow
Performs the given SQL query calling the givenclosurewith each row of the result set starting at the providedoffset, and including up tomaxRowsnumber of rows. The row will be aGroovyResultSetwhich is aResultSetthat supports accessing the fields using property style notation and ordinal index values. The query may contain GString expressions.Note that the underlying implementation is based on either invoking
ResultSet.absolute(), or if the ResultSet type isResultSet.TYPE_FORWARD_ONLY, theResultSet.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_ONLYmay be less efficient than a "scrollable" type.- Parameters:
gstring- a GString containing the SQL query with embedded paramsoffset- the 1-based offset for the first row to be processedmaxRows- the maximum number of rows to be processedclosure- called for each row with a GroovyResultSet- Throws:
SQLException- if a database access error occurs
-
eachRow
Performs the given SQL query calling the given Closure with each row of the result set. The row will be aGroovyResultSetwhich is aResultSetthat supports accessing the fields using property style notation and ordinal index values. The query may contain GString expressions.Example usage:
def location = 25 sql.eachRow("select * from PERSON where location_id < $location") { row -> println row.firstname }Resource handling is performed automatically where appropriate.
- Parameters:
gstring- a GString containing the SQL query with embedded paramsclosure- called for each row with a GroovyResultSet- Throws:
SQLException- if a database access error occurs- See Also:
-
rows
Performs the given SQL query and return the rows of the result set.Example usage:
def ans = sql.rows("select * from PERSON where firstname like 'S%'") println "Found ${ans.size()} rows"Resource handling is performed automatically where appropriate.
- Parameters:
sql- the SQL statement- Returns:
- a list of GroovyRowResult objects
- Throws:
SQLException- if a database access error occurs
-
rows
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.Note that the underlying implementation is based on either invoking
ResultSet.absolute(), or if the ResultSet type isResultSet.TYPE_FORWARD_ONLY, theResultSet.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_ONLYmay be less efficient than a "scrollable" type.Resource handling is performed automatically where appropriate.
- Parameters:
sql- the SQL statementoffset- the 1-based offset for the first row to be processedmaxRows- the maximum number of rows to be processed- Returns:
- a list of GroovyRowResult objects
- Throws:
SQLException- if a database access error occurs
-
rows
Performs the given SQL query and return the rows of the result set. In addition, themetaClosurewill be called once passing in theResultSetMetaDataas argument.Example usage:
def printNumCols = { meta -> println "Found $meta.columnCount columns" } def ans = sql.rows("select * from PERSON", printNumCols) println "Found ${ans.size()} rows"Resource handling is performed automatically where appropriate.
- Parameters:
sql- the SQL statementmetaClosure- called with meta data of the ResultSet- Returns:
- a list of GroovyRowResult objects
- Throws:
SQLException- if a database access error occurs
-
rows
public List<GroovyRowResult> rows(String sql, int offset, int maxRows, Closure metaClosure) throws SQLException 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, themetaClosurewill be called once passing in theResultSetMetaDataas argument.Note that the underlying implementation is based on either invoking
ResultSet.absolute(), or if the ResultSet type isResultSet.TYPE_FORWARD_ONLY, theResultSet.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_ONLYmay be less efficient than a "scrollable" type.Resource handling is performed automatically where appropriate.
- Parameters:
sql- 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)- Returns:
- a list of GroovyRowResult objects
- Throws:
SQLException- if a database access error occurs
-
rows
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
paramslist. See the class Javadoc for more details.Resource handling is performed automatically where appropriate.
- Parameters:
sql- the SQL statementparams- a list of parameters- Returns:
- a list of GroovyRowResult objects
- Throws:
SQLException- if a database access error occurs
-
rows
A variant ofrows(String, java.util.List)useful when providing the named parameters as named arguments.- Parameters:
params- a map containing the named parameterssql- the SQL statement- Returns:
- a list of GroovyRowResult objects
- Throws:
SQLException- if a database access error occurs- Since:
- 1.8.7
-
rows
public List<GroovyRowResult> rows(String sql, List<Object> params, int offset, int maxRows) throws SQLException 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. 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 isResultSet.TYPE_FORWARD_ONLY, theResultSet.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_ONLYmay be less efficient than a "scrollable" type.This method supports named and named ordinal parameters by supplying such parameters in the
paramslist. See the class Javadoc for more details.Resource handling is performed automatically where appropriate.
- Parameters:
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 processed- Returns:
- a list of GroovyRowResult objects
- Throws:
SQLException- if a database access error occurs
-
rows
public List<GroovyRowResult> rows(String sql, Map params, int offset, int maxRows) throws SQLException A variant ofrows(String, java.util.List, int, int)useful when providing the named parameters as a map.- Parameters:
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 processed- Returns:
- a list of GroovyRowResult objects
- Throws:
SQLException- if a database access error occurs- Since:
- 1.8.7
-
rows
public List<GroovyRowResult> rows(Map params, String sql, int offset, int maxRows) throws SQLException A variant ofrows(String, java.util.List, int, int)useful when providing the named parameters as named arguments.- Parameters:
params- a map of named parameterssql- the SQL statementoffset- the 1-based offset for the first row to be processedmaxRows- the maximum number of rows to be processed- Returns:
- a list of GroovyRowResult objects
- Throws:
SQLException- if a database access error occurs- Since:
- 1.8.7
-
rows
Performs the given SQL query and return the rows of the result set.This method supports named and named ordinal parameters by supplying such parameters in the
paramsarray. See the class Javadoc for more details.An Object array variant of
rows(String, List).- Parameters:
sql- the SQL statementparams- an array of parameters- Returns:
- a list of GroovyRowResult objects
- Throws:
SQLException- if a database access error occurs
-
rows
public List<GroovyRowResult> rows(String sql, Object[] params, int offset, int maxRows) throws SQLException Performs the given SQL query and return the rows of the result set.This method supports named and named ordinal parameters by supplying such parameters in the
paramsarray. See the class Javadoc for more details.An Object array variant of
rows(String, List, int, int).- Parameters:
sql- the SQL statementparams- an array of parametersoffset- the 1-based offset for the first row to be processedmaxRows- the maximum number of rows to be processed- Returns:
- a list of GroovyRowResult objects
- Throws:
SQLException- if a database access error occurs
-
rows
public List<GroovyRowResult> rows(String sql, List<Object> params, Closure metaClosure) throws SQLException Performs the given SQL query and return the rows of the result set. In addition, themetaClosurewill be called once passing in theResultSetMetaDataas argument. The query may contain placeholder question marks which match the given list of parameters.Example usage:
def printNumCols = { meta -> println "Found $meta.columnCount columns" } def ans = sql.rows("select * from PERSON where lastname like ?", ['%a%'], printNumCols) println "Found ${ans.size()} rows"This method supports named and named ordinal parameters by supplying such parameters in the
paramslist. Here is an example:def printNumCols = { meta -> println "Found $meta.columnCount columns" } def mapParam = [foo: 'Smith'] def domainParam = new MyDomainClass(bar: 'John') def qry = 'select * from PERSON where lastname=?1.foo and firstname=?2.bar' def ans = sql.rows(qry, [mapParam, domainParam], printNumCols) println "Found ${ans.size()} rows" def qry2 = 'select * from PERSON where firstname=:first and lastname=:last' def ans2 = sql.rows(qry2, [[last:'Smith', first:'John']], printNumCols) println "Found ${ans2.size()} rows"See the class Javadoc for more details.Resource handling is performed automatically where appropriate.
- Parameters:
sql- the SQL statementparams- a list of parametersmetaClosure- called for meta data (only once after sql execution)- Returns:
- a list of GroovyRowResult objects
- Throws:
SQLException- if a database access error occurs
-
rows
A variant ofrows(String, java.util.List, groovy.lang.Closure)useful when providing the named parameters as a map.- Parameters:
sql- the SQL statementparams- a map of named parametersmetaClosure- called for meta data (only once after sql execution)- Returns:
- a list of GroovyRowResult objects
- Throws:
SQLException- if a database access error occurs- Since:
- 1.8.7
-
rows
A variant ofrows(String, java.util.List, groovy.lang.Closure)useful when providing the named parameters as named arguments.- Parameters:
params- a map of named parameterssql- the SQL statementmetaClosure- called for meta data (only once after sql execution)- Returns:
- a list of GroovyRowResult objects
- Throws:
SQLException- if a database access error occurs- Since:
- 1.8.7
-
rows
public List<GroovyRowResult> rows(String sql, List<Object> params, int offset, int maxRows, Closure metaClosure) throws SQLException 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, themetaClosurewill be called once passing in theResultSetMetaDataas 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 isResultSet.TYPE_FORWARD_ONLY, theResultSet.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_ONLYmay be less efficient than a "scrollable" type.This method supports named and named ordinal parameters by supplying such parameters in the
paramslist. See the class Javadoc for more details.Resource handling is performed automatically where appropriate.
- Parameters:
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)- Returns:
- a list of GroovyRowResult objects
- Throws:
SQLException- if a database access error occurs
-
rows
public List<GroovyRowResult> rows(String sql, Map params, int offset, int maxRows, Closure metaClosure) throws SQLException A variant ofrows(String, java.util.List, int, int, groovy.lang.Closure)useful when providing the named parameters as a map.- Parameters:
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)- Returns:
- a list of GroovyRowResult objects
- Throws:
SQLException- if a database access error occurs- Since:
- 1.8.7
-
rows
public List<GroovyRowResult> rows(Map params, String sql, int offset, int maxRows, Closure metaClosure) throws SQLException A variant ofrows(String, java.util.List, int, int, groovy.lang.Closure)useful when providing the named parameters as named arguments.- Parameters:
params- a map of named parameterssql- 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)- Returns:
- a list of GroovyRowResult objects
- Throws:
SQLException- if a database access error occurs- Since:
- 1.8.7
-
rows
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. The query may contain GString expressions.Note that the underlying implementation is based on either invoking
ResultSet.absolute(), or if the ResultSet type isResultSet.TYPE_FORWARD_ONLY, theResultSet.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_ONLYmay be less efficient than a "scrollable" type.Resource handling is performed automatically where appropriate.
- Parameters:
sql- the SQL statementoffset- the 1-based offset for the first row to be processedmaxRows- the maximum number of rows to be processed- Returns:
- a list of GroovyRowResult objects
- Throws:
SQLException- if a database access error occurs
-
rows
Performs the given SQL query and return the rows of the result set. The query may contain GString expressions.Example usage:
def location = 25 def ans = sql.rows("select * from PERSON where location_id < $location") println "Found ${ans.size()} rows"Resource handling is performed automatically where appropriate.
- Parameters:
gstring- a GString containing the SQL query with embedded params- Returns:
- a list of GroovyRowResult objects
- Throws:
SQLException- if a database access error occurs- See Also:
-
rows
Performs the given SQL query and return the rows of the result set. In addition, themetaClosurewill be called once passing in theResultSetMetaDataas argument. The query may contain GString expressions.Example usage:
def location = 25 def printNumCols = { meta -> println "Found $meta.columnCount columns" } def ans = sql.rows("select * from PERSON where location_id < $location", printNumCols) println "Found ${ans.size()} rows"Resource handling is performed automatically where appropriate.
- Parameters:
gstring- a GString containing the SQL query with embedded paramsmetaClosure- called with meta data of the ResultSet- Returns:
- a list of GroovyRowResult objects
- Throws:
SQLException- if a database access error occurs- See Also:
-
rows
public List<GroovyRowResult> rows(GString gstring, int offset, int maxRows, Closure metaClosure) throws SQLException 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, themetaClosurewill be called once passing in theResultSetMetaDataas argument. The query may contain GString expressions.Note that the underlying implementation is based on either invoking
ResultSet.absolute(), or if the ResultSet type isResultSet.TYPE_FORWARD_ONLY, theResultSet.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_ONLYmay be less efficient than a "scrollable" type.Resource handling is performed automatically where appropriate.
- Parameters:
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)- Returns:
- a list of GroovyRowResult objects
- Throws:
SQLException- if a database access error occurs
-
firstRow
Performs the given SQL query and return the first row of the result set.Example usage:
def ans = sql.firstRow("select * from PERSON where firstname like 'S%'") println ans.firstnameResource handling is performed automatically where appropriate.
- Parameters:
sql- the SQL statement- Returns:
- a GroovyRowResult object or
nullif no row is found - Throws:
SQLException- if a database access error occurs
-
firstRow
Performs 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.firstnameResource handling is performed automatically where appropriate.
- Parameters:
gstring- a GString containing the SQL query with embedded params- Returns:
- a GroovyRowResult object or
nullif no row is found - Throws:
SQLException- if a database access error occurs- See Also:
-
firstRow
Performs the given SQL query and return the first row of the result set. The query may contain placeholder question marks which match the given list of parameters.Example usages:
def ans = sql.firstRow("select * from PERSON where lastname like ?", ['%a%']) println ans.firstnameIf your database returns scalar functions as ResultSets, you can also use firstRow to gain access to stored procedure results, e.g. using hsqldb 1.9 RC4:sql.execute """ create function FullName(p_firstname VARCHAR(40)) returns VARCHAR(80) BEGIN atomic DECLARE ans VARCHAR(80); SET ans = (SELECT firstname || ' ' || lastname FROM PERSON WHERE firstname = p_firstname); RETURN ans; END """ assert sql.firstRow("{call FullName(?)}", ['Sam'])[0] == 'Sam Pullara'This method supports named and named ordinal parameters by supplying such parameters in the
paramslist. See the class Javadoc for more details.Resource handling is performed automatically where appropriate.
- Parameters:
sql- the SQL statementparams- a list of parameters- Returns:
- a GroovyRowResult object or
nullif no row is found - Throws:
SQLException- if a database access error occurs
-
firstRow
A variant offirstRow(String, java.util.List)useful when providing the named parameters as named arguments.- Parameters:
params- a map containing the named parameterssql- the SQL statement- Returns:
- a GroovyRowResult object or
nullif no row is found - Throws:
SQLException- if a database access error occurs- Since:
- 1.8.7
-
firstRow
Performs the given SQL query and return the first row of the result set.An Object array variant of
firstRow(String, List).This method supports named and named ordinal parameters by supplying such parameters in the
paramsarray. See the class Javadoc for more details.- Parameters:
sql- the SQL statementparams- an array of parameters- Returns:
- a GroovyRowResult object or
nullif no row is found - Throws:
SQLException- if a database access error occurs
-
execute
Executes the given piece of SQL. Also saves the updateCount, if any, for subsequent examination.Example usages:
sql.execute "DROP TABLE IF EXISTS person" sql.execute """ CREATE TABLE person ( id INTEGER NOT NULL, firstname VARCHAR(100), lastname VARCHAR(100), location_id INTEGER ) """ sql.execute """ INSERT INTO person (id, firstname, lastname, location_id) VALUES (4, 'Paul', 'King', 40) """ assert sql.updateCount == 1Resource handling is performed automatically where appropriate.
- Parameters:
sql- the SQL to execute- Returns:
trueif the first result is aResultSetobject;falseif it is an update count or there are no results- Throws:
SQLException- if a database access error occurs
-
execute
Executes the given piece of SQL. Also calls the provided processResults Closure to process any ResultSet or UpdateCount results that executing the SQL might produce.Example usages:
boolean first = true sql.execute "{call FindAllByFirst('J')}", { isResultSet, result -> if (first) { first = false assert !isResultSet && result == 0 } else { assert isResultSet && result == [[ID:1, FIRSTNAME:'James', LASTNAME:'Strachan'], [ID:4, FIRSTNAME:'Jean', LASTNAME:'Gabin']] } }Resource handling is performed automatically where appropriate.
- Parameters:
sql- the SQL to executeprocessResults- a Closure which will be passed two parameters: eithertrueplus a list of GroovyRowResult values derived fromstatement.getResultSet()orfalseplus the update count fromstatement.getUpdateCount(). The closure will be called for each result produced from executing the SQL.- Throws:
SQLException- if a database access error occurs- Since:
- 2.3.2
-
execute
Executes 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 == 1This method supports named and named ordinal parameters. See the class Javadoc for more details.
Resource handling is performed automatically where appropriate.
- Parameters:
sql- the SQL statementparams- a list of parameters- Returns:
trueif the first result is aResultSetobject;falseif it is an update count or there are no results- Throws:
SQLException- if a database access error occurs
-
execute
Executes the given piece of SQL with parameters. Also calls the provided processResults Closure to process any ResultSet or UpdateCount results that executing the SQL might produce.This method supports named and named ordinal parameters. See the class Javadoc for more details.
Resource handling is performed automatically where appropriate.
- Parameters:
sql- the SQL statementparams- a list of parametersprocessResults- a Closure which will be passed two parameters: eithertrueplus a list of GroovyRowResult values derived fromstatement.getResultSet()orfalseplus the update count fromstatement.getUpdateCount(). The closure will be called for each result produced from executing the SQL.- Throws:
SQLException- if a database access error occurs- Since:
- 2.3.2
- See Also:
-
execute
A variant ofexecute(String, java.util.List)useful when providing the named parameters as named arguments.- Parameters:
params- a map containing the named parameterssql- the SQL statement- Returns:
trueif the first result is aResultSetobject;falseif it is an update count or there are no results- Throws:
SQLException- if a database access error occurs- Since:
- 1.8.7
-
execute
A variant ofexecute(String, java.util.List, Closure)useful when providing the named parameters as named arguments.- Parameters:
params- a map containing the named parameterssql- the SQL statementprocessResults- a Closure which will be passed two parameters: eithertrueplus a list of GroovyRowResult values derived fromstatement.getResultSet()orfalseplus the update count fromstatement.getUpdateCount(). The closure will be called for each result produced from executing the SQL.- Throws:
SQLException- if a database access error occurs- Since:
- 2.3.2
-
execute
Executes the given piece of SQL with parameters.An Object array variant of
execute(String, List).This method supports named and named ordinal parameters by supplying such parameters in the
paramsarray. See the class Javadoc for more details.- Parameters:
sql- the SQL statementparams- an array of parameters- Returns:
trueif the first result is aResultSetobject;falseif it is an update count or there are no results- Throws:
SQLException- if a database access error occurs
-
execute
Executes the given piece of SQL with parameters.An Object array variant of
execute(String, List, Closure).This method supports named and named ordinal parameters by supplying such parameters in the
paramsarray. See the class Javadoc for more details.- Parameters:
sql- the SQL statementparams- an array of parametersprocessResults- a Closure which will be passed two parameters: eithertrueplus a list of GroovyRowResult values derived fromstatement.getResultSet()orfalseplus the update count fromstatement.getUpdateCount(). The closure will be called for each result produced from executing the SQL.- Throws:
SQLException- if a database access error occurs- Since:
- 2.3.2
- See Also:
-
execute
Executes the given SQL with embedded expressions inside. Also saves the updateCount, if any, for subsequent examination.Example usage:
def scott = [firstname: "Scott", lastname: "Davis", id: 5, location_id: 50] sql.execute """ insert into PERSON (id, firstname, lastname, location_id) values ($scott.id, $scott.firstname, $scott.lastname, $scott.location_id) """ assert sql.updateCount == 1Resource handling is performed automatically where appropriate.
- Parameters:
gstring- a GString containing the SQL query with embedded params- Returns:
trueif the first result is aResultSetobject;falseif it is an update count or there are no results- Throws:
SQLException- if a database access error occurs- See Also:
-
execute
Executes the given SQL with embedded expressions inside. Also calls the provided processResults Closure to process any ResultSet or UpdateCount results that executing the SQL might produce. Resource handling is performed automatically where appropriate.- Parameters:
gstring- a GString containing the SQL query with embedded paramsprocessResults- a Closure which will be passed two parameters: eithertrueplus a list of GroovyRowResult values derived fromstatement.getResultSet()orfalseplus the update count fromstatement.getUpdateCount(). The closure will be called for each result produced from executing the SQL.- Throws:
SQLException- if a database access error occurs- Since:
- 2.3.2
- See Also:
-
executeInsert
Executes 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. SeeexecuteInsert(GString)for more details.Resource handling is performed automatically where appropriate.
- Parameters:
sql- The SQL statement to execute- Returns:
- A list of the auto-generated column values for each inserted row (typically auto-generated keys)
- Throws:
SQLException- if a database access error occurs
-
executeInsert
public
-
buildSqlWithIndexedProps(String)instead