Groovy Sql and Oracle ‘Invalid column index’ SQLException

There are some minor potential dangers associated with Groovy’s def keyword. The Groovy style and language feature guidelines for Java developers provides some warnings about use of def. In this blog post, I demonstrate an advantage of being more explicit in typing when using Groovy SQL with an Oracle database to avoid a potential “Invalid column indexSQLException because I’ve run into this issue a few times.

The following Groovy script provides comments on Oracle database tables matching a provided search string. In this case, what the script does is not as important as look at the code that defines the SQL query string (lines 18-21).

searchDbComments.groovy (using def without String typing or as String)

#!/usr/bin/env groovy
// searchDbComments.groovy

this.class.classLoader.rootLoader.addURL(
   new URL("file:///C:/oraclexe/app/oracle/product/11.2.0/server/jdbc/lib/ojdbc6.jar"))

if (args.length < 1)
{
   println "USAGE: searchDbComments.groovy <searchString>"
   System.exit(-1)
}

def searchString = args[0].toUpperCase()

import groovy.sql.Sql
def sql = Sql.newInstance("jdbc:oracle:thin:@localhost:1521:xe", "hr", "hr",
                          "oracle.jdbc.pool.OracleDataSource")
def dbTableCommentsQry = """
SELECT table_name, table_type, comments
  FROM user_tab_comments
 WHERE UPPER(comments) LIKE '%${searchString}%'"""

sql.eachRow(dbTableCommentsQry)
{
   println "${it.table_name} (${it.table_type}): ${it.comments}"
}

When the above code is executed, the following error is generated:

WARNING: Failed to execute: 
SELECT table_name, table_type, comments
  FROM user_tab_comments
 WHERE UPPER(comments) LIKE '%?%' because: Invalid column index

Caught: java.sql.SQLException: Invalid column index

java.sql.SQLException: Invalid column index
    at oracle.jdbc.driver.OraclePreparedStatement.setStringInternal(OraclePreparedStatement.java:5303)
    at oracle.jdbc.driver.OraclePreparedStatement.setObjectCritical(OraclePreparedStatement.java:8323)
    at oracle.jdbc.driver.OraclePreparedStatement.setObjectInternal(OraclePreparedStatement.java:8259)
    at oracle.jdbc.driver.OraclePreparedStatement.setObjectInternal(OraclePreparedStatement.java:9012)
    at oracle.jdbc.driver.OraclePreparedStatement.setObject(OraclePreparedStatement.java:8993)
    at oracle.jdbc.driver.OraclePreparedStatementWrapper.setObject(OraclePreparedStatementWrapper.java:230)
    at searchDbComments.run(searchDbComments.groovy:23)

Addressing the “invalid column index” SQLException is easy. One solution is to change the “def” on lines 18-21 to an explicit “String” type. Another solution, shown in the next code listing, is to use Groovy’s “as” coercion keyword to explicitly allow the “def” to be used and have the dbTableCommentsQry variable be typed as a String.

searchDbComments.groovy (using as String)

#!/usr/bin/env groovy
// searchDbComments.groovy

this.class.classLoader.rootLoader.addURL(
   new URL("file:///C:/oraclexe/app/oracle/product/11.2.0/server/jdbc/lib/ojdbc6.jar"))

if (args.length < 1)
{
   println "USAGE: searchDbComments.groovy <searchString>"
   System.exit(-1)
}

def searchString = args[0].toUpperCase()

import groovy.sql.Sql
def sql = Sql.newInstance("jdbc:oracle:thin:@localhost:1521:xe", "hr", "hr",
                          "oracle.jdbc.pool.OracleDataSource")
def dbTableCommentsQry = """
SELECT table_name, table_type, comments
  FROM user_tab_comments
 WHERE UPPER(comments) LIKE '%${searchString}%'""" as String

sql.eachRow(dbTableCommentsQry)
{
   println "${it.table_name} (${it.table_type}): ${it.comments}"
}

Using “def” only or no “def” with no type at all leads to the above error. Explicitly defining the String variable used in the query either via static typing or via use of “as” keyword allows the code to execute properly. One could use a static typing with “def”, but that is thought to be redundant.

There is nothing necessarily wrong about using “def,” but one does need to be careful with its application. Guillaume Laforge has written that “def is fine in method bodies or for particular dynamic aspects, but for everything that is a ‘contract’ (method signatures, properties, etc), it’s better to use explicit types.”
 

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

Leave a Reply


6 − = two



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close