public class Sql
extends java.lang.Object
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.
Modifier and Type | Class and Description |
---|---|
protected class |
Sql.AbstractQueryCommand |
Modifier and Type | Field and 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 java.util.logging.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(java.sql.Connection connection)
Constructs an SQL instance using the given Connection.
|
Sql(javax.sql.DataSource dataSource)
Constructs an SQL instance using the given DataSource.
|
Sql(Sql parent) |
Modifier and Type | Method and Description |
---|---|
static InParameter |
ARRAY(java.lang.Object value) |
protected java.util.List<GroovyRowResult> |
asList(java.lang.String sql,
java.sql.ResultSet rs)
Hook to allow derived classes to override list of result collection behavior.
|
protected java.util.List<GroovyRowResult> |
asList(java.lang.String sql,
java.sql.ResultSet rs,
Closure metaClosure)
Hook to allow derived classes to override list of result collection behavior.
|
protected java.util.List<GroovyRowResult> |
asList(java.lang.String sql,
java.sql.ResultSet rs,
int offset,
int maxRows,
Closure metaClosure) |
protected java.lang.String |
asSql(GString gstring,
java.util.List<java.lang.Object> values)
Hook to allow derived classes to override sql generation from GStrings.
|
static InParameter |
BIGINT(java.lang.Object value) |
static InParameter |
BINARY(java.lang.Object value) |
static InParameter |
BIT(java.lang.Object value) |
static InParameter |
BLOB(java.lang.Object value) |
static InParameter |
BOOLEAN(java.lang.Object value) |
void |
cacheConnection(Closure closure)
Caches the connection used while the closure is active.
|
void |
cacheStatements(Closure closure)
Caches every created preparedStatement in Closure closure
Every cached preparedStatement is closed after closure has been called.
|
int |
call(GString gstring)
Performs a stored procedure call with the given embedded parameters.
|
void |
call(GString gstring,
Closure closure)
Performs a stored procedure call with the given parameters,
calling the closure once with all result objects.
|
int |
call(java.lang.String sql)
Performs a stored procedure call.
|
int |
call(java.lang.String sql,
java.util.List<java.lang.Object> params)
Performs a stored procedure call with the given parameters.
|
void |
call(java.lang.String sql,
java.util.List<java.lang.Object> params,
Closure closure)
Performs a stored procedure call with the given parameters.
|
int |
call(java.lang.String sql,
java.lang.Object[] params)
Performs a stored procedure call with the given parameters.
|
static InParameter |
CHAR(java.lang.Object value) |
SqlWithParams |
checkForNamedParams(java.lang.String sql,
java.util.List<java.lang.Object> params) |
static InParameter |
CLOB(java.lang.Object value) |
void |
close()
If this SQL object was created with a Connection then this method closes
the connection.
|
protected void |
closeResources(java.sql.Connection connection)
An extension point allowing the behavior of resource closing to be
overridden in derived classes.
|
protected void |
closeResources(java.sql.Connection connection,
java.sql.Statement statement)
An extension point allowing the behavior of resource closing to be
overridden in derived classes.
|
protected void |
closeResources(java.sql.Connection connection,
java.sql.Statement statement,
java.sql.ResultSet results)
An extension point allowing derived classes to change the behavior
of resource closing.
|
void |
commit()
If this SQL object was created with a Connection then this method commits
the connection.
|
protected void |
configure(java.sql.Statement statement)
Provides a hook for derived classes to be able to configure JDBC statements.
|
protected java.sql.Connection |
createConnection()
An extension point allowing derived classes to change the behavior of
connection creation.
|
protected Sql.AbstractQueryCommand |
createPreparedQueryCommand(java.lang.String sql,
java.util.List<java.lang.Object> queryParams)
Factory for the PreparedQueryCommand command pattern object allows subclass to supply implementations
of the command class.
|
protected Sql.AbstractQueryCommand |
createQueryCommand(java.lang.String sql)
Factory for the QueryCommand command pattern object allows subclasses to
supply implementations of the command class.
|
static InParameter |
DATALINK(java.lang.Object value) |
DataSet |
dataSet(java.lang.Class<?> type) |
DataSet |
dataSet(java.lang.String table) |
static InParameter |
DATE(java.lang.Object value) |
static InParameter |
DECIMAL(java.lang.Object value) |
static InParameter |
DISTINCT(java.lang.Object value) |
static InParameter |
DOUBLE(java.lang.Object value) |
void |
eachRow(GString gstring,
Closure closure)
Performs the given SQL query calling the given Closure with each row of the result set.
|
void |
eachRow(GString gstring,
Closure metaClosure,
Closure rowClosure)
Performs the given SQL query calling the given Closure with each row of the result set.
|
void |
eachRow(GString gstring,
Closure metaClosure,
int offset,
int maxRows,
Closure rowClosure)
Performs the given SQL query calling the given
closure with each row of the result set starting at
the provided offset , and including up to maxRows number of rows. |
void |
eachRow(GString gstring,
int offset,
int maxRows,
Closure closure)
Performs the given SQL query calling the given
closure with each row of the result set starting at
the provided offset , and including up to maxRows number of rows. |
void |
eachRow(java.util.Map params,
java.lang.String sql,
Closure closure)
A variant of
eachRow(String, java.util.List, groovy.lang.Closure)
useful when providing the named parameters as named arguments. |
void |
eachRow(java.util.Map params,
java.lang.String sql,
Closure metaClosure,
Closure rowClosure)
A variant of
eachRow(String, java.util.List, groovy.lang.Closure, groovy.lang.Closure)
useful when providing the named parameters as named arguments. |
void |
eachRow(java.util.Map map,
java.lang.String sql,
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 as named arguments. |
void |
eachRow(java.util.Map params,
java.lang.String sql,
int offset,
int maxRows,
Closure closure)
A variant of
eachRow(String, java.util.List, int, int, groovy.lang.Closure)
useful when providing the named parameters as named arguments. |
void |
eachRow(java.lang.String sql,
Closure closure)
Performs the given SQL query calling the given Closure with each row of the result set.
|
void |
eachRow(java.lang.String sql,
Closure metaClosure,
Closure rowClosure)
Performs the given SQL query calling the given
rowClosure with each row of the
result set. |
void |
eachRow(java.lang.String sql,
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(java.lang.String sql,
int offset,
int maxRows,
Closure closure)
Performs the given SQL query calling the given
closure with each row of the result set starting at
the provided offset , and including up to maxRows number of rows. |
void |
eachRow(java.lang.String sql,
java.util.List<java.lang.Object> params,
Closure closure)
Performs the given SQL query calling the given Closure with each row of the result set.
|
void |
eachRow(java.lang.String sql,
java.util.List<java.lang.Object> params,
Closure metaClosure,
Closure rowClosure)
Performs the given SQL query calling the given Closure with each row of the result set.
|
void |
eachRow(java.lang.String sql,
java.util.List<java.lang.Object> 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(java.lang.String sql,
java.util.List<java.lang.Object> params,
int offset,
int maxRows,
Closure closure)
Performs the given SQL query calling the given
closure with each row of the result set starting at
the provided offset , and including up to maxRows number of rows. |
void |
eachRow(java.lang.String sql,
java.util.Map params,
Closure closure)
A variant of
eachRow(String, java.util.List, groovy.lang.Closure)
useful when providing the named parameters as a map. |
void |
eachRow(java.lang.String sql,
java.util.Map params,
Closure metaClosure,
Closure rowClosure)
A variant of
eachRow(String, java.util.List, groovy.lang.Closure, groovy.lang.Closure)
useful when providing the named parameters as a map. |
void |
eachRow(java.lang.String sql,
java.util.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(java.lang.String sql,
java.util.Map params,
int offset,
int maxRows,
Closure closure)
A variant of
eachRow(String, java.util.List, int, int, groovy.lang.Closure)
useful when providing the named parameters as a map. |
boolean |
execute(GString gstring)
Executes the given SQL with embedded expressions inside.
|
boolean |
execute(java.util.Map params,
java.lang.String sql)
A variant of
execute(String, java.util.List)
useful when providing the named parameters as named arguments. |
boolean |
execute(java.lang.String sql)
Executes the given piece of SQL.
|
boolean |
execute(java.lang.String sql,
java.util.List<java.lang.Object> params)
Executes the given piece of SQL with parameters.
|
boolean |
execute(java.lang.String sql,
java.lang.Object[] params)
Executes the given piece of SQL with parameters.
|
java.util.List<java.util.List<java.lang.Object>> |
executeInsert(GString gstring)
Executes the given SQL statement (typically an INSERT statement).
|
java.util.List<java.util.List<java.lang.Object>> |
executeInsert(java.util.Map params,
java.lang.String sql)
A variant of
firstRow(String, java.util.List)
useful when providing the named parameters as named arguments. |
java.util.List<java.util.List<java.lang.Object>> |
executeInsert(java.lang.String sql)
Executes the given SQL statement (typically an INSERT statement).
|
java.util.List<java.util.List<java.lang.Object>> |
executeInsert(java.lang.String sql,
java.util.List<java.lang.Object> params)
Executes the given SQL statement (typically an INSERT statement).
|
java.util.List<java.util.List<java.lang.Object>> |
executeInsert(java.lang.String sql,
java.lang.Object[] params)
Executes the given SQL statement (typically an INSERT statement).
|
protected java.sql.ResultSet |
executePreparedQuery(java.lang.String sql,
java.util.List<java.lang.Object> params)
Useful helper method which handles resource management when executing a
prepared query which returns a result set.
|
protected java.sql.ResultSet |
executeQuery(java.lang.String sql)
Useful helper method which handles resource management when executing a
query which returns a result set.
|
int |
executeUpdate(GString gstring)
Executes the given SQL update with embedded expressions inside.
|
int |
executeUpdate(java.util.Map params,
java.lang.String sql)
A variant of
executeUpdate(String, java.util.List)
useful when providing the named parameters as named arguments. |
int |
executeUpdate(java.lang.String sql)
Executes the given SQL update.
|
int |
executeUpdate(java.lang.String sql,
java.util.List<java.lang.Object> params)
Executes the given SQL update with parameters.
|
int |
executeUpdate(java.lang.String sql,
java.lang.Object[] params)
Executes the given SQL update with parameters.
|
static ExpandedVariable |
expand(java.lang.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(java.lang.String sql)
Hook to allow derived classes to override where clause sniffing.
|
GroovyRowResult |
firstRow(GString gstring)
Performs the given SQL query and return
the first row of the result set.
|
GroovyRowResult |
firstRow(java.util.Map params,
java.lang.String sql)
A variant of
firstRow(String, java.util.List)
useful when providing the named parameters as named arguments. |
GroovyRowResult |
firstRow(java.lang.String sql)
Performs the given SQL query and return the first row of the result set.
|
GroovyRowResult |
firstRow(java.lang.String sql,
java.util.List<java.lang.Object> params)
Performs the given SQL query and return the first row of the result set.
|
GroovyRowResult |
firstRow(java.lang.String sql,
java.lang.Object[] params)
Performs the given SQL query and return the first row of the result set.
|
static InParameter |
FLOAT(java.lang.Object value) |
java.sql.Connection |
getConnection()
If this instance was created with a single Connection then the connection
is returned.
|
javax.sql.DataSource |
getDataSource() |
protected java.util.List<java.lang.Object> |
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() |
java.util.List<java.lang.Object> |
getUpdatedParams(java.util.List<java.lang.Object> params,
java.util.List<Tuple> indexPropList) |
static InParameter |
in(int type,
java.lang.Object value)
Create a new InParameter
|
static InOutParameter |
inout(InParameter in)
Create an inout parameter using this in parameter.
|
static InParameter |
INTEGER(java.lang.Object value) |
boolean |
isCacheNamedQueries() |
boolean |
isCacheStatements() |
boolean |
isEnableNamedQueries() |
boolean |
isWithinBatch()
Returns true if the current Sql object is currently executing a withBatch
method call.
|
static InParameter |
JAVA_OBJECT(java.lang.Object value) |
static void |
loadDriver(java.lang.String driverClassName)
Attempts to load the JDBC driver on the thread, current or system class
loaders
|
static InParameter |
LONGVARBINARY(java.lang.Object value) |
static InParameter |
LONGVARCHAR(java.lang.Object value) |
static Sql |
newInstance(java.util.Map<java.lang.String,java.lang.Object> args)
Creates a new Sql instance given parameters in a Map.
|
static Sql |
newInstance(java.lang.String url)
Creates a new Sql instance given a JDBC connection URL.
|
static Sql |
newInstance(java.lang.String url,
java.util.Properties properties)
Creates a new Sql instance given a JDBC connection URL
and some properties.
|
static Sql |
newInstance(java.lang.String url,
java.util.Properties properties,
java.lang.String driverClassName)
Creates a new Sql instance given a JDBC connection URL,
some properties and a driver class name.
|
static Sql |
newInstance(java.lang.String url,
java.lang.String driverClassName)
Creates a new Sql instance given a JDBC connection URL
and a driver class name.
|
static Sql |
newInstance(java.lang.String url,
java.lang.String user,
java.lang.String password)
Creates a new Sql instance given a JDBC connection URL,
a username and a password.
|
static Sql |
newInstance(java.lang.String url,
java.lang.String user,
java.lang.String password,
java.lang.String driverClassName)
Creates a new Sql instance given a JDBC connection URL,
a username, a password and a driver class name.
|
static InParameter |
NULL(java.lang.Object value) |
protected java.lang.String |
nullify(java.lang.String sql)
Hook to allow derived classes to override null handling.
|
static InParameter |
NUMERIC(java.lang.Object value) |
static InParameter |
OTHER(java.lang.Object value) |
static OutParameter |
out(int type)
Create a new OutParameter
|
SqlWithParams |
preCheckForNamedParams(java.lang.String sql) |
void |
query(GString gstring,
Closure closure)
Performs the given SQL query, which should return a single
ResultSet object. |
void |
query(java.util.Map map,
java.lang.String sql,
Closure closure)
A variant of
query(String, java.util.List, groovy.lang.Closure)
useful when providing the named parameters as named arguments. |
void |
query(java.lang.String sql,
Closure closure)
Performs the given SQL query, which should return a single
ResultSet object. |
void |
query(java.lang.String sql,
java.util.List<java.lang.Object> params,
Closure closure)
Performs the given SQL query, which should return a single
ResultSet object. |
void |
query(java.lang.String sql,
java.util.Map map,
Closure closure)
A variant of
query(String, java.util.List, groovy.lang.Closure)
useful when providing the named parameters as a map. |
static InParameter |
REAL(java.lang.Object value) |
static InParameter |
REF(java.lang.Object value) |
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.
|
java.util.List<GroovyRowResult> |
rows(GString gstring)
Performs the given SQL query and return the rows of the result set.
|
java.util.List<GroovyRowResult> |
rows(GString gstring,
Closure metaClosure)
Performs the given SQL query and return the rows of the result set.
|
java.util.List<GroovyRowResult> |
rows(GString sql,
int offset,
int maxRows)
Performs the given SQL query and return a "page" of rows from the result set.
|
java.util.List<GroovyRowResult> |
rows(GString gstring,
int offset,
int maxRows,
Closure metaClosure)
Performs the given SQL query and return a "page" of rows from the result set.
|
java.util.List<GroovyRowResult> |
rows(java.util.Map params,
java.lang.String sql)
A variant of
rows(String, java.util.List)
useful when providing the named parameters as named arguments. |
java.util.List<GroovyRowResult> |
rows(java.util.Map params,
java.lang.String sql,
Closure metaClosure)
A variant of
rows(String, java.util.List, groovy.lang.Closure)
useful when providing the named parameters as named arguments. |
java.util.List<GroovyRowResult> |
rows(java.util.Map params,
java.lang.String sql,
int offset,
int maxRows)
A variant of
rows(String, java.util.List, int, int)
useful when providing the named parameters as named arguments. |
java.util.List<GroovyRowResult> |
rows(java.util.Map params,
java.lang.String sql,
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 named arguments. |
java.util.List<GroovyRowResult> |
rows(java.lang.String sql)
Performs the given SQL query and return the rows of the result set.
|
java.util.List<GroovyRowResult> |
rows(java.lang.String sql,
Closure metaClosure)
Performs the given SQL query and return the rows of the result set.
|
java.util.List<GroovyRowResult> |
rows(java.lang.String sql,
int offset,
int maxRows)
Performs the given SQL query and return a "page" of rows from the result set.
|
java.util.List<GroovyRowResult> |
rows(java.lang.String sql,
int offset,
int maxRows,
Closure metaClosure)
Performs the given SQL query and return a "page" of rows from the result set.
|
java.util.List<GroovyRowResult> |
rows(java.lang.String sql,
java.util.List<java.lang.Object> params)
Performs the given SQL query and return the rows of the result set.
|
java.util.List<GroovyRowResult> |
rows(java.lang.String sql,
java.util.List<java.lang.Object> params,
Closure metaClosure)
Performs the given SQL query and return the rows of the result set.
|
java.util.List<GroovyRowResult> |
rows(java.lang.String sql,
java.util.List<java.lang.Object> params,
int offset,
int maxRows)
Performs the given SQL query and return a "page" of rows from the result set.
|
java.util.List<GroovyRowResult> |
rows(java.lang.String sql,
java.util.List<java.lang.Object> params,
int offset,
int maxRows,
Closure metaClosure)
Performs the given SQL query and return a "page" of rows from the result set.
|
java.util.List<GroovyRowResult> |
rows(java.lang.String sql,
java.util.Map params,
Closure metaClosure)
A variant of
rows(String, java.util.List, groovy.lang.Closure)
useful when providing the named parameters as a map. |
java.util.List<GroovyRowResult> |
rows(java.lang.String sql,
java.util.Map params,
int offset,
int maxRows)
A variant of
rows(String, java.util.List, int, int)
useful when providing the named parameters as a map. |
java.util.List<GroovyRowResult> |
rows(java.lang.String sql,
java.util.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. |
java.util.List<GroovyRowResult> |
rows(java.lang.String sql,
java.lang.Object[] params)
Performs the given SQL query and return the rows of the result set.
|
java.util.List<GroovyRowResult> |
rows(java.lang.String sql,
java.lang.Object[] params,
int offset,
int maxRows)
Performs the given SQL query and return the rows of the result set.
|
void |
setCacheNamedQueries(boolean cacheNamedQueries)
Enables named query caching.
|
void |
setCacheStatements(boolean cacheStatements)
Enables statement caching.
|
void |
setEnableNamedQueries(boolean enableNamedQueries)
Enables named query support.
|
protected void |
setInternalConnection(java.sql.Connection conn)
Stub needed for testing.
|
protected void |
setObject(java.sql.PreparedStatement statement,
int i,
java.lang.Object value)
Strategy method allowing derived classes to handle types differently
such as for CLOBs etc.
|
protected void |
setParameters(java.util.List<java.lang.Object> params,
java.sql.PreparedStatement statement)
Hook to allow derived classes to override behavior associated with
setting params for a prepared statement.
|
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.
|
static InParameter |
SMALLINT(java.lang.Object value) |
static InParameter |
STRUCT(java.lang.Object value) |
static InParameter |
TIME(java.lang.Object value) |
static InParameter |
TIMESTAMP(java.lang.Object value) |
static InParameter |
TINYINT(java.lang.Object value) |
static InParameter |
VARBINARY(java.lang.Object value) |
static InParameter |
VARCHAR(java.lang.Object value) |
int[] |
withBatch(Closure closure)
Performs the closure (containing batch operations) within a batch.
|
int[] |
withBatch(int batchSize,
Closure closure)
Performs the closure (containing batch operations) within a batch using a given batch size.
|
int[] |
withBatch(int batchSize,
java.lang.String sql,
Closure closure)
Performs the closure (containing batch operations specific to an associated prepared statement)
within a batch using a given batch size.
|
int[] |
withBatch(java.lang.String sql,
Closure closure)
Performs the closure (containing batch operations specific to an associated prepared statement)
within a batch.
|
static void |
withInstance(java.util.Map<java.lang.String,java.lang.Object> args,
Closure c)
Invokes a closure passing it a new Sql instance created from the given map of arguments.
|
static void |
withInstance(java.lang.String url,
Closure c)
Invokes a closure passing it a new Sql instance created from the given JDBC connection URL.
|
static void |
withInstance(java.lang.String url,
java.util.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(java.lang.String url,
java.util.Properties properties,
java.lang.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(java.lang.String url,
java.lang.String driverClassName,
Closure c)
Invokes a closure passing it a new Sql instance created from the given JDBC connection URL.
|
static void |
withInstance(java.lang.String url,
java.lang.String user,
java.lang.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(java.lang.String url,
java.lang.String user,
java.lang.String password,
java.lang.String driverClassName,
Closure c)
Invokes a closure passing it a new Sql instance created from the given JDBC connection URL.
|
void |
withStatement(Closure configureStatement)
Allows a closure to be passed in to configure the JDBC statements before they are executed.
|
void |
withTransaction(Closure closure)
Performs the closure within a transaction using a cached connection.
|
protected static final java.util.logging.Logger LOG
public static final OutParameter ARRAY
public static final OutParameter BIGINT
public static final OutParameter BINARY
public static final OutParameter BIT
public static final OutParameter BLOB
public static final OutParameter BOOLEAN
public static final OutParameter CHAR
public static final OutParameter CLOB
public static final OutParameter DATALINK
public static final OutParameter DATE
public static final OutParameter DECIMAL
public static final OutParameter DISTINCT
public static final OutParameter DOUBLE
public static final OutParameter FLOAT
public static final OutParameter INTEGER
public static final OutParameter JAVA_OBJECT
public static final OutParameter LONGVARBINARY
public static final OutParameter LONGVARCHAR
public static final OutParameter NULL
public static final OutParameter NUMERIC
public static final OutParameter OTHER
public static final OutParameter REAL
public static final OutParameter REF
public static final OutParameter SMALLINT
public static final OutParameter STRUCT
public static final OutParameter TIME
public static final OutParameter TIMESTAMP
public static final OutParameter TINYINT
public static final OutParameter VARBINARY
public static final OutParameter VARCHAR
public Sql(javax.sql.DataSource dataSource)
dataSource
- the DataSource to usepublic Sql(java.sql.Connection connection)
close()
method which will close the connection but also
free any caches resources.connection
- the Connection to usepublic Sql(Sql parent)
public static Sql newInstance(java.lang.String url) throws java.sql.SQLException
url
- a database url of the form
jdbc:subprotocol:subname
java.sql.SQLException
- if a database access error occurspublic static void withInstance(java.lang.String url, Closure c) throws java.sql.SQLException
url
- a database url of the form
jdbc:subprotocol:subname
c
- the Closure to calljava.sql.SQLException
- if a database access error occursnewInstance(String)
public static Sql newInstance(java.lang.String url, java.util.Properties properties) throws java.sql.SQLException
url
- a database url of the form
jdbc:subprotocol:subname
properties
- a list of arbitrary string tag/value pairs
as connection arguments; normally at least a "user" and
"password" property should be includedjava.sql.SQLException
- if a database access error occurspublic static void withInstance(java.lang.String url, java.util.Properties properties, Closure c) throws java.sql.SQLException
url
- a database url of the form
jdbc:subprotocol:subname
properties
- 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 calljava.sql.SQLException
- if a database access error occursnewInstance(String, java.util.Properties)
public static Sql newInstance(java.lang.String url, java.util.Properties properties, java.lang.String driverClassName) throws java.sql.SQLException, java.lang.ClassNotFoundException
url
- a database url of the form
jdbc:subprotocol:subname
properties
- 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 classjava.sql.SQLException
- if a database access error occursjava.lang.ClassNotFoundException
- if the driver class cannot be found or loadedpublic static void withInstance(java.lang.String url, java.util.Properties properties, java.lang.String driverClassName, Closure c) throws java.sql.SQLException, java.lang.ClassNotFoundException
url
- a database url of the form
jdbc:subprotocol:subname
properties
- 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 calljava.sql.SQLException
- if a database access error occursjava.lang.ClassNotFoundException
- if the driver class cannot be found or loadednewInstance(String, java.util.Properties, String)
public static Sql newInstance(java.lang.String url, java.lang.String user, java.lang.String password) throws java.sql.SQLException
url
- a database url of the form
jdbc:subprotocol:subname
user
- the database user on whose behalf the connection
is being madepassword
- the user's passwordjava.sql.SQLException
- if a database access error occurspublic static void withInstance(java.lang.String url, java.lang.String user, java.lang.String password, Closure c) throws java.sql.SQLException
url
- a database url of the form
jdbc:subprotocol:subname
user
- the database user on whose behalf the connection
is being madepassword
- the user's passwordc
- the Closure to calljava.sql.SQLException
- if a database access error occursnewInstance(String, String, String)
public static Sql newInstance(java.lang.String url, java.lang.String user, java.lang.String password, java.lang.String driverClassName) throws java.sql.SQLException, java.lang.ClassNotFoundException
url
- a database url of the form
jdbc:subprotocol:subname
user
- the database user on whose behalf the connection
is being madepassword
- the user's passworddriverClassName
- the fully qualified class name of the driver classjava.sql.SQLException
- if a database access error occursjava.lang.ClassNotFoundException
- if the driver class cannot be found or loadedpublic static void withInstance(java.lang.String url, java.lang.String user, java.lang.String password, java.lang.String driverClassName, Closure c) throws java.sql.SQLException, java.lang.ClassNotFoundException
url
- a database url of the form
jdbc:subprotocol:subname
user
- 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 calljava.sql.SQLException
- if a database access error occursjava.lang.ClassNotFoundException
- if the driver class cannot be found or loadednewInstance(String, String, String, String)
public static Sql newInstance(java.lang.String url, java.lang.String driverClassName) throws java.sql.SQLException, java.lang.ClassNotFoundException
url
- a database url of the form
jdbc:subprotocol:subname
driverClassName
- the fully qualified class name of the driver classjava.sql.SQLException
- if a database access error occursjava.lang.ClassNotFoundException
- if the driver class cannot be found or loadedpublic static void withInstance(java.lang.String url, java.lang.String driverClassName, Closure c) throws java.sql.SQLException, java.lang.ClassNotFoundException
url
- a database url of the form
jdbc:subprotocol:subname
driverClassName
- the fully qualified class name of the driver classc
- the Closure to calljava.sql.SQLException
- if a database access error occursjava.lang.ClassNotFoundException
- if the driver class cannot be found or loadednewInstance(String, String)
public static Sql newInstance(java.util.Map<java.lang.String,java.lang.Object> args) throws java.sql.SQLException, java.lang.ClassNotFoundException
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 argumentsjava.sql.SQLException
- if a database access error occursjava.lang.ClassNotFoundException
- if the driver class cannot be found or loadedpublic static void withInstance(java.util.Map<java.lang.String,java.lang.Object> args, Closure c) throws java.sql.SQLException, java.lang.ClassNotFoundException
args
- a Map contain further argumentsc
- the Closure to calljava.sql.SQLException
- if a database access error occursjava.lang.ClassNotFoundException
- if the driver class cannot be found or loadednewInstance(java.util.Map)
public int getResultSetType()
public void setResultSetType(int resultSetType)
resultSetType
- one of the following ResultSet
constants:
ResultSet.TYPE_FORWARD_ONLY
,
ResultSet.TYPE_SCROLL_INSENSITIVE
, or
ResultSet.TYPE_SCROLL_SENSITIVE
public int getResultSetConcurrency()
public void setResultSetConcurrency(int resultSetConcurrency)
resultSetConcurrency
- one of the following ResultSet
constants:
ResultSet.CONCUR_READ_ONLY
or
ResultSet.CONCUR_UPDATABLE
public int getResultSetHoldability()
public void setResultSetHoldability(int resultSetHoldability)
resultSetHoldability
- one of the following ResultSet
constants:
ResultSet.HOLD_CURSORS_OVER_COMMIT
or
ResultSet.CLOSE_CURSORS_AT_COMMIT
public static void loadDriver(java.lang.String driverClassName) throws java.lang.ClassNotFoundException
driverClassName
- the fully qualified class name of the driver classjava.lang.ClassNotFoundException
- if the class cannot be found or loadedpublic static InParameter ARRAY(java.lang.Object value)
public static InParameter BIGINT(java.lang.Object value)
public static InParameter BINARY(java.lang.Object value)
public static InParameter BIT(java.lang.Object value)
public static InParameter BLOB(java.lang.Object value)
public static InParameter BOOLEAN(java.lang.Object value)
public static InParameter CHAR(java.lang.Object value)
public static InParameter CLOB(java.lang.Object value)
public static InParameter DATALINK(java.lang.Object value)
public static InParameter DATE(java.lang.Object value)
public static InParameter DECIMAL(java.lang.Object value)
public static InParameter DISTINCT(java.lang.Object value)
public static InParameter DOUBLE(java.lang.Object value)
public static InParameter FLOAT(java.lang.Object value)
public static InParameter INTEGER(java.lang.Object value)
public static InParameter JAVA_OBJECT(java.lang.Object value)
public static InParameter LONGVARBINARY(java.lang.Object value)
public static InParameter LONGVARCHAR(java.lang.Object value)
public static InParameter NULL(java.lang.Object value)
public static InParameter NUMERIC(java.lang.Object value)
public static InParameter OTHER(java.lang.Object value)
public static InParameter REAL(java.lang.Object value)
public static InParameter REF(java.lang.Object value)
public static InParameter SMALLINT(java.lang.Object value)
public static InParameter STRUCT(java.lang.Object value)
public static InParameter TIME(java.lang.Object value)
public static InParameter TIMESTAMP(java.lang.Object value)
public static InParameter TINYINT(java.lang.Object value)
public static InParameter VARBINARY(java.lang.Object value)
public static InParameter VARCHAR(java.lang.Object value)
public static InParameter in(int type, java.lang.Object value)
type
- the JDBC data typevalue
- the object valuepublic static OutParameter out(int type)
type
- the JDBC data type.public static InOutParameter inout(InParameter in)
in
- the InParameter of interestpublic static ResultSetOutParameter resultSet(int type)
type
- the JDBC data type.public static ExpandedVariable expand(java.lang.Object object)
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 interestexpand(Object)
public DataSet dataSet(java.lang.String table)
public DataSet dataSet(java.lang.Class<?> type)
public void query(java.lang.String sql, Closure closure) throws java.sql.SQLException
ResultSet
object. The given closure is called
with the ResultSet
as 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.
sql
- the sql statementclosure
- called for each row with a GroovyResultSetjava.sql.SQLException
- if a database access error occurspublic void query(java.lang.String sql, java.util.List<java.lang.Object> params, Closure closure) throws java.sql.SQLException
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 GroovyResultSetjava.sql.SQLException
- if a database access error occurspublic void query(java.lang.String sql, java.util.Map map, Closure closure) throws java.sql.SQLException
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 GroovyResultSetjava.sql.SQLException
- if a database access error occurspublic void query(java.util.Map map, java.lang.String sql, Closure closure) throws java.sql.SQLException
query(String, java.util.List, groovy.lang.Closure)
useful when providing the named parameters as named arguments.map
- a map containing the named parameterssql
- the sql statementclosure
- called for each row with a GroovyResultSetjava.sql.SQLException
- if a database access error occurspublic void query(GString gstring, Closure closure) throws java.sql.SQLException
ResultSet
object. The given closure is called
with the ResultSet
as 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.
gstring
- a GString containing the SQL query with embedded paramsclosure
- called for each row with a GroovyResultSetjava.sql.SQLException
- if a database access error occursexpand(Object)
public void eachRow(java.lang.String sql, Closure closure) throws java.sql.SQLException
GroovyResultSet
which is a ResultSet
that 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.
sql
- the sql statementclosure
- called for each row with a GroovyResultSetjava.sql.SQLException
- if a database access error occurspublic void eachRow(java.lang.String sql, int offset, int maxRows, Closure closure) throws java.sql.SQLException
closure
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.
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.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 GroovyResultSetjava.sql.SQLException
- if a database access error occurspublic void eachRow(java.lang.String sql, Closure metaClosure, Closure rowClosure) throws java.sql.SQLException
rowClosure
with each row of the
result set.
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.
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.
sql
- the sql statementmetaClosure
- called for meta data (only once after sql execution)rowClosure
- called for each row with a GroovyResultSetjava.sql.SQLException
- if a database access error occurspublic void eachRow(java.lang.String sql, Closure metaClosure, int offset, int maxRows, Closure rowClosure) throws java.sql.SQLException
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.
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.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 GroovyResultSetjava.sql.SQLException
- if a database access error occurspublic void eachRow(java.lang.String sql, java.util.List<java.lang.Object> params, Closure metaClosure, int offset, int maxRows, Closure rowClosure) throws java.sql.SQLException
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 GroovyResultSetjava.sql.SQLException
- if a database access error occurspublic void eachRow(java.lang.String sql, java.util.Map map, Closure metaClosure, int offset, int maxRows, Closure rowClosure) throws java.sql.SQLException
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 GroovyResultSetjava.sql.SQLException
- if a database access error occurspublic void eachRow(java.util.Map map, java.lang.String sql, Closure metaClosure, int offset, int maxRows, Closure rowClosure) throws java.sql.SQLException
eachRow(String, java.util.List, groovy.lang.Closure, int, int, groovy.lang.Closure)
allowing the named parameters to be supplied as named arguments.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 GroovyResultSetjava.sql.SQLException
- if a database access error occurspublic void eachRow(java.lang.String sql, java.util.List<java.lang.Object> params, Closure metaClosure, Closure rowClosure) throws java.sql.SQLException
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.
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.
sql
- the sql statementparams
- a list of parametersmetaClosure
- called for meta data (only once after sql execution)rowClosure
- called for each row with a GroovyResultSetjava.sql.SQLException
- if a database access error occurspublic void eachRow(java.lang.String sql, java.util.Map params, Closure metaClosure, Closure rowClosure) throws java.sql.SQLException
eachRow(String, java.util.List, groovy.lang.Closure, groovy.lang.Closure)
useful when providing the named parameters as a map.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 GroovyResultSetjava.sql.SQLException
- if a database access error occurspublic void eachRow(java.util.Map params, java.lang.String sql, Closure metaClosure, Closure rowClosure) throws java.sql.SQLException
eachRow(String, java.util.List, groovy.lang.Closure, groovy.lang.Closure)
useful when providing the named parameters as named arguments.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 GroovyResultSetjava.sql.SQLException
- if a database access error occurspublic void eachRow(java.lang.String sql, java.util.List<java.lang.Object> params, Closure closure) throws java.sql.SQLException
GroovyResultSet
which is a ResultSet
that 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.
sql
- the sql statementparams
- a list of parametersclosure
- called for each row with a GroovyResultSetjava.sql.SQLException
- if a database access error occurspublic void eachRow(java.lang.String sql, java.util.Map params, Closure closure) throws java.sql.SQLException
eachRow(String, java.util.List, groovy.lang.Closure)
useful when providing the named parameters as a map.sql
- the sql statementparams
- a map of named parametersclosure
- called for each row with a GroovyResultSetjava.sql.SQLException
- if a database access error occurspublic void eachRow(java.util.Map params, java.lang.String sql, Closure closure) throws java.sql.SQLException
eachRow(String, java.util.List, groovy.lang.Closure)
useful when providing the named parameters as named arguments.params
- a map of named parameterssql
- the sql statementclosure
- called for each row with a GroovyResultSetjava.sql.SQLException
- if a database access error occurspublic void eachRow(java.lang.String sql, java.util.List<java.lang.Object> params, int offset, int maxRows, Closure closure) throws java.sql.SQLException
closure
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.
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 processedclosure
- called for each row with a GroovyResultSetjava.sql.SQLException
- if a database access error occurspublic void eachRow(java.lang.String sql, java.util.Map params, int offset, int maxRows, Closure closure) throws java.sql.SQLException
eachRow(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 processedclosure
- called for each row with a GroovyResultSetjava.sql.SQLException
- if a database access error occurspublic void eachRow(java.util.Map params, java.lang.String sql, int offset, int maxRows, Closure closure) throws java.sql.SQLException
eachRow(String, java.util.List, int, int, groovy.lang.Closure)
useful when providing the named parameters as named arguments.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 GroovyResultSetjava.sql.SQLException
- if a database access error occurspublic void eachRow(GString gstring, Closure metaClosure, Closure rowClosure) throws java.sql.SQLException
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 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.
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 GroovyResultSetjava.sql.SQLException
- if a database access error occursexpand(Object)
public void eachRow(GString gstring, Closure metaClosure, int offset, int maxRows, Closure rowClosure) throws java.sql.SQLException
closure
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 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.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 GroovyResultSetjava.sql.SQLException
- if a database access error occurspublic void eachRow(GString gstring, int offset, int maxRows, Closure closure) throws java.sql.SQLException
closure
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.
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.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 GroovyResultSetjava.sql.SQLException
- if a database access error occurspublic void eachRow(GString gstring, Closure closure) throws java.sql.SQLException
GroovyResultSet
which is a ResultSet
that 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.
gstring
- a GString containing the SQL query with embedded paramsclosure
- called for each row with a GroovyResultSetjava.sql.SQLException
- if a database access error occursexpand(Object)
public java.util.List<GroovyRowResult> rows(java.lang.String sql) throws java.sql.SQLException
def ans = sql.rows("select * from PERSON where firstname like 'S%'") println "Found ${ans.size()} rows"Resource handling is performed automatically where appropriate.
sql
- the SQL statementjava.sql.SQLException
- if a database access error occurspublic java.util.List<GroovyRowResult> rows(java.lang.String sql, int offset, int maxRows) throws java.sql.SQLException
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.sql
- the SQL statementoffset
- the 1-based offset for the first row to be processedmaxRows
- the maximum number of rows to be processedjava.sql.SQLException
- if a database access error occurspublic java.util.List<GroovyRowResult> rows(java.lang.String sql, Closure metaClosure) throws java.sql.SQLException
metaClosure
will be called once passing in the
ResultSetMetaData
as 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.
sql
- the SQL statementmetaClosure
- called with meta data of the ResultSetjava.sql.SQLException
- if a database access error occurspublic java.util.List<GroovyRowResult> rows(java.lang.String sql, int offset, int maxRows, Closure metaClosure) throws java.sql.SQLException
metaClosure
will be called once passing in the
ResultSetMetaData
as argument.
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.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)java.sql.SQLException
- if a database access error occurspublic java.util.List<GroovyRowResult> rows(java.lang.String sql, java.util.List<java.lang.Object> params) throws java.sql.SQLException
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 parametersjava.sql.SQLException
- if a database access error occurspublic java.util.List<GroovyRowResult> rows(java.util.Map params, java.lang.String sql) throws java.sql.SQLException
rows(String, java.util.List)
useful when providing the named parameters as named arguments.params
- a map containing the named parameterssql
- the SQL statementjava.sql.SQLException
- if a database access error occurspublic java.util.List<GroovyRowResult> rows(java.lang.String sql, java.util.List<java.lang.Object> params, int offset, int maxRows) throws java.sql.SQLException
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.
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 parametersoffset
- the 1-based offset for the first row to be processedmaxRows
- the maximum number of rows to be processedjava.sql.SQLException
- if a database access error occurspublic java.util.List<GroovyRowResult> rows(java.lang.String sql, java.util.Map params, int offset, int maxRows) throws java.sql.SQLException
rows(String, java.util.List, int, int)
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 processedjava.sql.SQLException
- if a database access error occurspublic java.util.List<GroovyRowResult> rows(java.util.Map params, java.lang.String sql, int offset, int maxRows) throws java.sql.SQLException
rows(String, java.util.List, int, int)
useful when providing the named parameters as named arguments.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 processedjava.sql.SQLException
- if a database access error occurspublic java.util.List<GroovyRowResult> rows(java.lang.String sql, java.lang.Object[] params) throws java.sql.SQLException
params
array. See the class Javadoc for more details.
An Object array variant of rows(String, List)
.sql
- the SQL statementparams
- an array of parametersjava.sql.SQLException
- if a database access error occurspublic java.util.List<GroovyRowResult> rows(java.lang.String sql, java.lang.Object[] params, int offset, int maxRows) throws java.sql.SQLException
params
array. See the class Javadoc for more details.
An Object array variant of rows(String, List, int, int)
.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 processedjava.sql.SQLException
- if a database access error occurspublic java.util.List<GroovyRowResult> rows(java.lang.String sql, java.util.List<java.lang.Object> params, Closure metaClosure) throws java.sql.SQLException
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.
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
params
list. 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.
sql
- the SQL statementparams
- a list of parametersmetaClosure
- called for meta data (only once after sql execution)java.sql.SQLException
- if a database access error occurspublic java.util.List<GroovyRowResult> rows(java.lang.String sql, java.util.Map params, Closure metaClosure) throws java.sql.SQLException
rows(String, java.util.List, groovy.lang.Closure)
useful when providing the named parameters as a map.sql
- the SQL statementparams
- a map of named parametersmetaClosure
- called for meta data (only once after sql execution)java.sql.SQLException
- if a database access error occurspublic java.util.List<GroovyRowResult> rows(java.util.Map params, java.lang.String sql, Closure metaClosure) throws java.sql.SQLException
rows(String, java.util.List, groovy.lang.Closure)
useful when providing the named parameters as named arguments.params
- a map of named parameterssql
- the SQL statementmetaClosure
- called for meta data (only once after sql execution)java.sql.SQLException
- if a database access error occurspublic java.util.List<GroovyRowResult> rows(java.lang.String sql, java.util.List<java.lang.Object> params, int offset, int maxRows, Closure metaClosure) throws java.sql.SQLException
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.
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 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)java.sql.SQLException
- if a database access error occurspublic java.util.List<GroovyRowResult> rows(java.lang.String sql, java.util.Map params, int offset, int maxRows, Closure metaClosure) throws java.sql.SQLException
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)java.sql.SQLException
- if a database access error occurspublic java.util.List<GroovyRowResult> rows(java.util.Map params, java.lang.String sql, int offset, int maxRows, Closure metaClosure) throws java.sql.SQLException
rows(String, java.util.List, int, int, groovy.lang.Closure)
useful when providing the named parameters as named arguments.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)java.sql.SQLException
- if a database access error occurspublic java.util.List<GroovyRowResult> rows(GString sql, int offset, int maxRows) throws java.sql.SQLException
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.sql
- the SQL statementoffset
- the 1-based offset for the first row to be processedmaxRows
- the maximum number of rows to be processedjava.sql.SQLException
- if a database access error occurspublic java.util.List<GroovyRowResult> rows(GString gstring) throws java.sql.SQLException
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.
gstring
- a GString containing the SQL query with embedded paramsjava.sql.SQLException
- if a database access error occursexpand(Object)
public java.util.List<GroovyRowResult> rows(GString gstring, Closure metaClosure) throws java.sql.SQLException
metaClosure
will be called once passing in the
ResultSetMetaData
as 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.
gstring
- a GString containing the SQL query with embedded paramsmetaClosure
- called with meta data of the ResultSetjava.sql.SQLException
- if a database access error occursexpand(Object)
public java.util.List<GroovyRowResult> rows(GString gstring, int offset, int maxRows, Closure metaClosure) throws java.sql.SQLException
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)java.sql.SQLException
- if a database access error occurspublic GroovyRowResult firstRow(java.lang.String sql) throws java.sql.SQLException
def ans = sql.firstRow("select * from PERSON where firstname like 'S%'") println ans.firstnameResource handling is performed automatically where appropriate.
sql
- the SQL statementnull
if no row is foundjava.sql.SQLException
- if a database access error occurspublic GroovyRowResult firstRow(GString gstring) throws java.sql.SQLException
def location = 25 def ans = sql.firstRow("select * from PERSON where location_id < $location") println ans.firstnameResource handling is performed automatically where appropriate.
gstring
- a GString containing the SQL query with embedded paramsnull
if no row is foundjava.sql.SQLException
- if a database access error occursexpand(Object)
public GroovyRowResult firstRow(java.lang.String sql, java.util.List<java.lang.Object> params) throws java.sql.SQLException
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
params
list. See the class Javadoc for more details.
Resource handling is performed automatically where appropriate.sql
- the SQL statementparams
- a list of parametersnull
if no row is foundjava.sql.SQLException
- if a database access error occurspublic GroovyRowResult firstRow(java.util.Map params, java.lang.String sql) throws java.sql.SQLException
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 foundjava.sql.SQLException
- if a database access error occurspublic GroovyRowResult firstRow(java.lang.String sql, java.lang.Object[] params) throws java.sql.SQLException
firstRow(String, List)
.
This method supports named and named ordinal parameters by supplying such
parameters in the params
array. See the class Javadoc for more details.sql
- the SQL statementparams
- an array of parametersnull
if no row is foundjava.sql.SQLException
- if a database access error occurspublic boolean execute(java.lang.String sql) throws java.sql.SQLException
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.
sql
- the SQL to executetrue
if the first result is a ResultSet
object; false
if it is an update count or there are
no resultsjava.sql.SQLException
- if a database access error occurspublic boolean execute(java.lang.String sql, java.util.List<java.lang.Object> params) throws java.sql.SQLException
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.
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 resultsjava.sql.SQLException
- if a database access error occurspublic boolean execute(java.util.Map params, java.lang.String sql) throws java.sql.SQLException
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 resultsjava.sql.SQLException
- if a database access error occurspublic boolean execute(java.lang.String sql, java.lang.Object[] params) throws java.sql.SQLException
execute(String, List)
.
This method supports named and named ordinal parameters by supplying such
parameters in the params
array. See the class Javadoc for more details.sql
- the SQL statementparams
- an array of parameterstrue
if the first result is a ResultSet
object; false
if it is an update count or there are
no resultsjava.sql.SQLException
- if a database access error occurspublic boolean execute(GString gstring) throws java.sql.SQLException
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.
gstring
- a GString containing the SQL query with embedded paramstrue
if the first result is a ResultSet
object; false
if it is an update count or there are
no resultsjava.sql.SQLException
- if a database access error occursexpand(Object)
public java.util.List<java.util.List<java.lang.Object>> executeInsert(java.lang.String sql) throws java.sql.SQLException
executeInsert(GString)
for more details.
Resource handling is performed automatically where appropriate.sql
- The SQL statement to executejava.sql.SQLException
- if a database access error occurspublic java.util.List<java.util.List<java.lang.Object>> executeInsert(java.lang.String sql, java.util.List<java.lang.Object> params) throws java.sql.SQLException
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 slotsjava.sql.SQLException
- if a database access error occurspublic java.util.List<java.util.List<java.lang.Object>> executeInsert(java.util.Map params, java.lang.String sql) throws java.sql.SQLException
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 executejava.sql.SQLException
- if a database access error occurspublic java.util.List<java.util.List<java.lang.Object>> executeInsert(java.lang.String sql, java.lang.Object[] params) throws java.sql.SQLException
executeInsert(String, List)
.
This method supports named and named ordinal parameters by supplying such
parameters in the params
array. See the class Javadoc for more details.sql
- The SQL statement to executeparams
- The parameter values that will be substituted
into the SQL statement's parameter slotsjava.sql.SQLException
- if a database access error occurspublic java.util.List<java.util.List<java.lang.Object>> executeInsert(GString gstring) throws java.sql.SQLException
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. The query may contain GString expressions.
Generated key values can be accessed using
array notation. For example, to return the second auto-generated
column value of the third row, use keys[3][1]
. The
method is designed to be used with SQL INSERT statements, but is
not limited to them.
The standard use for this method is when a table has an autoincrement ID column and you want to know what the ID is for a newly inserted row. In this example, we insert a single row into a table in which the first column contains the autoincrement ID:
def sql = Sql.newInstance("jdbc:mysql://localhost:3306/groovy", "user", "password", "com.mysql.jdbc.Driver") def keys = sql.executeInsert("insert into test_table (INT_DATA, STRING_DATA) " + "VALUES (1, 'Key Largo')") def id = keys[0][0] // 'id' now contains the value of the new row's ID column. // It can be used to update an object representation's // id attribute for example. ...Resource handling is performed automatically where appropriate.
gstring
- a GString containing the SQL query with embedded paramsjava.sql.SQLException
- if a database access error occursexpand(Object)
public int executeUpdate(java.lang.String sql) throws java.sql.SQLException
sql
- the SQL to executejava.sql.SQLException
- if a database access error occurspublic int executeUpdate(java.lang.String sql, java.util.List<java.lang.Object> params) throws java.sql.SQLException
sql
- the SQL statementparams
- a list of parametersjava.sql.SQLException
- if a database access error occurspublic int executeUpdate(java.util.Map params, java.lang.String sql) throws java.sql.SQLException
executeUpdate(String, java.util.List)
useful when providing the named parameters as named arguments.params
- a map containing the named parameterssql
- the SQL statementjava.sql.SQLException
- if a database access error occurspublic int executeUpdate(java.lang.String sql, java.lang.Object[] params) throws java.sql.SQLException
executeUpdate(String, List)
.sql
- the SQL statementparams
- an array of parametersjava.sql.SQLException
- if a database access error occurspublic int executeUpdate(GString gstring) throws java.sql.SQLException
gstring
- a GString containing the SQL query with embedded paramsjava.sql.SQLException
- if a database access error occursexpand(Object)
public int call(java.lang.String sql) throws java.lang.Exception
sql.execute """ CREATE PROCEDURE HouseSwap(_first1 VARCHAR(50), _first2 VARCHAR(50)) BEGIN DECLARE _loc1 INT; DECLARE _loc2 INT; SELECT location_id into _loc1 FROM PERSON where firstname = _first1; SELECT location_id into _loc2 FROM PERSON where firstname = _first2; UPDATE PERSON set location_id = case firstname when _first1 then _loc2 when _first2 then _loc1 end where (firstname = _first1 OR firstname = _first2); END """then you can invoke the procedure as follows:
def rowsChanged = sql.call("{call HouseSwap('Guillaume', 'Paul')}") assert rowsChanged == 2
sql
- the SQL statementjava.sql.SQLException
- if a database access error occursjava.lang.Exception
public int call(GString gstring) throws java.lang.Exception
call(String)
for more details about
creating a HouseSwap(IN name1, IN name2)
stored procedure.
Once created, it can be called like this:
def p1 = 'Paul' def p2 = 'Guillaume' def rowsChanged = sql.call("{call HouseSwap($p1, $p2)}") assert rowsChanged == 2Resource handling is performed automatically where appropriate.
gstring
- a GString containing the SQL query with embedded paramsjava.sql.SQLException
- if a database access error occursjava.lang.Exception
expand(Object)
,
call(String)
public int call(java.lang.String sql, java.util.List<java.lang.Object> params) throws java.lang.Exception
call(String)
for more details about
creating a HouseSwap(IN name1, IN name2)
stored procedure.
Once created, it can be called like this:
def rowsChanged = sql.call("{call HouseSwap(?, ?)}", ['Guillaume', 'Paul']) assert rowsChanged == 2Resource handling is performed automatically where appropriate.
sql
- the SQL statementparams
- a list of parametersjava.sql.SQLException
- if a database access error occursjava.lang.Exception
call(String)
public int call(java.lang.String sql, java.lang.Object[] params) throws java.lang.Exception
call(String, List)
.sql
- the SQL statementparams
- an array of parametersjava.sql.SQLException
- if a database access error occursjava.lang.Exception
call(String)
public void call(java.lang.String sql, java.util.List<java.lang.Object> params, Closure closure) throws java.lang.Exception
// Tested with MySql 5.0.75 sql.execute """ CREATE PROCEDURE Hemisphere( IN p_firstname VARCHAR(50), IN p_lastname VARCHAR(50), OUT ans VARCHAR(50)) BEGIN DECLARE loc INT; SELECT location_id into loc FROM PERSON where firstname = p_firstname and lastname = p_lastname; CASE loc WHEN 40 THEN SET ans = 'Southern Hemisphere'; ELSE SET ans = 'Northern Hemisphere'; END CASE; END; """we can now call the stored procedure as follows:
sql.call '{call Hemisphere(?, ?, ?)}', ['Guillaume', 'Laforge', Sql.VARCHAR], { dwells -> println dwells }which will output '
Northern Hemisphere
'.
We can also access stored functions with scalar return values where the return value
will be treated as an OUT parameter. Here are examples for various databases for
creating such a procedure:
// Tested with MySql 5.0.75 sql.execute """ create function FullName(p_firstname VARCHAR(40)) returns VARCHAR(80) begin declare ans VARCHAR(80); SELECT CONCAT(firstname, ' ', lastname) INTO ans FROM PERSON WHERE firstname = p_firstname; return ans; end """ // Tested with MS SQLServer Express 2008 sql.execute """and here is how you access the stored function for all databases:create function FullName(@firstname VARCHAR(40)) returns VARCHAR(80)
begin declare@ans
VARCHAR(80)SET @ans = (SELECT firstname + ' ' + lastname FROM PERSON WHERE firstname = @firstname)
return@ans
end """ // Tested with Oracle XE 10g sql.execute """ create function FullName(p_firstname VARCHAR) return VARCHAR is ans VARCHAR(80); begin SELECT CONCAT(CONCAT(firstname, ' '), lastname) INTO ans FROM PERSON WHERE firstname = p_firstname; return ans; end; """
sql.call("{? = call FullName(?)}", [Sql.VARCHAR, 'Sam']) { name -> assert name == 'Sam Pullara' }Resource handling is performed automatically where appropriate.
sql
- the sql statementparams
- a list of parametersclosure
- called for each row with a GroovyResultSetjava.sql.SQLException
- if a database access error occursjava.lang.Exception
public void call(GString gstring, Closure closure) throws java.lang.Exception
call(String, List, Closure)
for more details about
creating a Hemisphere(IN first, IN last, OUT dwells)
stored procedure.
Once created, it can be called like this:
def first = 'Scott' def last = 'Davis' sql.call "{call Hemisphere($first, $last, ${Sql.VARCHAR})}", { dwells -> println dwells }As another example, see
call(String, List, Closure)
for more details about
creating a FullName(IN first)
stored function.
Once created, it can be called like this:
def first = 'Sam' sql.call("{$Sql.VARCHAR = call FullName($first)}") { name -> assert name == 'Sam Pullara' }Resource handling is performed automatically where appropriate.
gstring
- a GString containing the SQL query with embedded paramsclosure
- called for each row with a GroovyResultSetjava.sql.SQLException
- if a database access error occursjava.lang.Exception
call(String, List, Closure)
,
expand(Object)
public void close()
public javax.sql.DataSource getDataSource()
public void commit() throws java.sql.SQLException
java.sql.SQLException
- if a database access error occurspublic void rollback() throws java.sql.SQLException
java.sql.SQLException
- if a database access error occurspublic int getUpdateCount()
public java.sql.Connection getConnection()
public void withStatement(Closure configureStatement)
sql.withStatement{ stmt -> stmt.maxRows = 10 } def firstTenRows = sql.rows("select * from table")
configureStatement
- the closurepublic void setCacheStatements(boolean cacheStatements)
cacheStatements
- the new valuepublic boolean isCacheStatements()
public void cacheConnection(Closure closure) throws java.sql.SQLException
closure
- the given closurejava.sql.SQLException
- if a database error occurspublic void withTransaction(Closure closure) throws java.sql.SQLException
closure
- the given closurejava.sql.SQLException
- if a database error occurspublic boolean isWithinBatch()
public int[] withBatch(Closure closure) throws java.sql.SQLException
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 database
statement (actually a BatchingStatementWrapper
helper object)
associated with this batch.
Use it like this:
def updateCounts = sql.withBatch { stmt -> stmt.addBatch("insert into TABLENAME ...") stmt.addBatch("insert into TABLENAME ...") stmt.addBatch("insert into TABLENAME ...") ... }For integrity and performance reasons, you may wish to consider executing your batch command(s) within a transaction:
sql.withTransaction { def result1 = sql.withBatch { ... } ... }
closure
- the closure containing batch and optionally other statementsjava.sql.SQLException
- if a database access error occurs,
or this method is called on a closed 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.withBatch(int, Closure)
public int[] withBatch(int batchSize, Closure closure) throws java.sql.SQLException
batchSize
addBatch(sqlBatchOperation)
operations, automatically calls an executeBatch()
operation to "chunk" up the database operations
into partitions. Though not normally needed, you can also explicitly call executeBatch()
which
after executing the current batch, resets the batch count back to zero.
The closure will be called with a single argument; the database statement
(actually a BatchingStatementWrapper
helper object)
associated with this batch.
Use it like this for batchSize of 20:
def updateCounts = sql.withBatch(20) { stmt -> stmt.addBatch("insert into TABLENAME ...") stmt.addBatch("insert into TABLENAME ...") stmt.addBatch("insert into TABLENAME ...") ... }For integrity and performance reasons, you may wish to consider executing your batch command(s) within a transaction:
sql.withTransaction { def result1 = sql.withBatch { ... } ... }
batchSize
- partition the batch into batchSize pieces, i.e. after batchSize
addBatch()
invocations, call executeBatch()
automatically;
0 means manual calls to executeBatch are requiredclosure
- the closure containing batch and optionally other statementsjava.sql.SQLException
- if a database access error occurs,
or this method is called on a closed 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.withBatch(Closure)
,
BatchingStatementWrapper
,
Statement
public int[] withBatch(java.lang.String sql, Closure closure) throws java.sql.SQLException
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 { ... } ... }
sql
- batch update statementclosure
- the closure containing batch statements (to bind parameters) and optionally other statementsjava.sql.SQLException
- if a database access error occurs,
or this method is called on a closed 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.withBatch(int, String, Closure)
,
BatchingPreparedStatementWrapper
,
PreparedStatement
public int[] withBatch(int batchSize, java.lang.String sql, Closure closure) throws java.sql.SQLException
batchSize
addBatch(params)
operations, automatically calls an executeBatch()
operation to "chunk" up the database operations
into partitions. Though not normally needed, you can also explicitly call executeBatch()
which
after executing the current batch, resets the batch count back to zero.
The closure will be called with a single argument; the prepared
statement (actually a BatchingPreparedStatementWrapper
helper object)
associated with this batch.
Below is an example using a batchSize of 20:
def updateCounts = sql.withBatch(20, 'insert into TABLENAME(a, b, c) values (?, ?, ?)') { ps -> ps.addBatch(10, 12, 5) // varargs style ps.addBatch([7, 3, 98]) // list ps.addBatch([22, 67, 11]) ... }Named parameters (into maps or domain objects) are also supported:
def updateCounts = sql.withBatch(20, 'insert into TABLENAME(a, b, c) values (:foo, :bar, :baz)') { ps -> ps.addBatch([foo:10, bar:12, baz:5]) // map ps.addBatch(foo:7, bar:3, baz:98) // Groovy named args allow outer brackets to be dropped ... }Named ordinal parameters (into maps or domain objects) are also supported:
def updateCounts = sql.withBatch(20, 'insert into TABLENAME(a, b, c) values (?1.foo, ?2.bar, ?2.baz)') { ps -> ps.addBatch([[foo:22], [bar:67, baz:11]]) // list of maps or domain objects ps.addBatch([foo:10], [bar:12, baz:5]) // varargs allows outer brackets to be dropped ps.addBatch([foo:7], [bar:3, baz:98]) ... } // swap to batch size of 5 and illustrate simple and domain object cases ... class Person { String first, last } def updateCounts2 = sql.withBatch(5, 'insert into PERSON(id, first, last) values (?1, ?2.first, ?2.last)') { ps -> ps.addBatch(1, new Person(first:'Peter', last:'Pan')) ps.addBatch(2, new Person(first:'Snow', last:'White')) ... }For integrity and performance reasons, you may wish to consider executing your batch command(s) within a transaction:
sql.withTransaction { def result1 = sql.withBatch { ... } ... }
batchSize
- partition the batch into batchSize pieces, i.e. after batchSize
addBatch()
invocations, call executeBatch()
automatically;
0 means manual calls to executeBatch are required if additional partitioning of the batch is requiredsql
- batch update statementclosure
- the closure containing batch statements (to bind parameters) and optionally other statementsjava.sql.SQLException
- if a database access error occurs,
or this method is called on a closed 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.BatchingPreparedStatementWrapper
,
PreparedStatement
public void cacheStatements(Closure closure) throws java.sql.SQLException
closure
- the given closurejava.sql.SQLException
- if a database error occurssetCacheStatements(boolean)
protected final java.sql.ResultSet executeQuery(java.lang.String sql) throws java.sql.SQLException
sql
- query to executejava.sql.SQLException
- if a database error occursprotected final java.sql.ResultSet executePreparedQuery(java.lang.String sql, java.util.List<java.lang.Object> params) throws java.sql.SQLException
sql
- query to executeparams
- parameters matching question mark placeholders in the queryjava.sql.SQLException
- if a database error occursprotected java.util.List<GroovyRowResult> asList(java.lang.String sql, java.sql.ResultSet rs) throws java.sql.SQLException
sql
- query to executers
- the ResultSet to processjava.sql.SQLException
- if a database error occursprotected java.util.List<GroovyRowResult> asList(java.lang.String sql, java.sql.ResultSet rs, Closure metaClosure) throws java.sql.SQLException
sql
- query to executers
- the ResultSet to processmetaClosure
- called for meta data (only once after sql execution)java.sql.SQLException
- if a database error occursprotected java.util.List<GroovyRowResult> asList(java.lang.String sql, java.sql.ResultSet rs, int offset, int maxRows, Closure metaClosure) throws java.sql.SQLException
java.sql.SQLException
protected java.lang.String asSql(GString gstring, java.util.List<java.lang.Object> values)
gstring
- a GString containing the SQL query with embedded paramsvalues
- the values to embedexpand(Object)
protected java.lang.String nullify(java.lang.String sql)
sql
- the SQL statementprotected int findWhereKeyword(java.lang.String sql)
sql
- the SQL statementprotected java.util.List<java.lang.Object> getParameters(GString gstring)
gstring
- a GString containing the SQL query with embedded paramsexpand(Object)
protected void setParameters(java.util.List<java.lang.Object> params, java.sql.PreparedStatement statement) throws java.sql.SQLException
setObject
.params
- the parameters to appendstatement
- the statementjava.sql.SQLException
- if a database access error occursprotected void setObject(java.sql.PreparedStatement statement, int i, java.lang.Object value) throws java.sql.SQLException
statement
- the statement of interesti
- the index of the object of interestvalue
- the new object valuejava.sql.SQLException
- if a database access error occursprotected java.sql.Connection createConnection() throws java.sql.SQLException
java.sql.SQLException
- if a SQL error occursprotected void closeResources(java.sql.Connection connection, java.sql.Statement statement, java.sql.ResultSet results)
connection
- the connection to closestatement
- the statement to closeresults
- the results to closeprotected void closeResources(java.sql.Connection connection, java.sql.Statement statement)
connection
- the connection to closestatement
- the statement to closeprotected void closeResources(java.sql.Connection connection)
connection
- the connection to closeprotected void configure(java.sql.Statement statement)
statement
- the statement to configurepublic SqlWithParams checkForNamedParams(java.lang.String sql, java.util.List<java.lang.Object> params)
public SqlWithParams preCheckForNamedParams(java.lang.String sql)
public java.util.List<java.lang.Object> getUpdatedParams(java.util.List<java.lang.Object> params, java.util.List<Tuple> indexPropList)
public boolean isCacheNamedQueries()
public void setCacheNamedQueries(boolean cacheNamedQueries)
cacheNamedQueries
- the new valuepublic boolean isEnableNamedQueries()
public void setEnableNamedQueries(boolean enableNamedQueries)
enableNamedQueries
- the new valueprotected Sql.AbstractQueryCommand createQueryCommand(java.lang.String sql)
AbstractQueryCommand q = createQueryCommand("update TABLE set count = 0) where count is null"); try { ResultSet rs = q.execute(); return asList(rs); } finally { q.closeResources(); }
sql
- statement to be executedprotected Sql.AbstractQueryCommand createPreparedQueryCommand(java.lang.String sql, java.util.List<java.lang.Object> queryParams)
sql
- statement to be executed, including optional parameter placeholders (?)queryParams
- List of parameter values corresponding to parameter placeholderscreateQueryCommand(String)
protected void setInternalConnection(java.sql.Connection conn)
conn
- the connection that is about to be used by a command