connecting groovy to sql server

Drake picture Drake · Sep 9, 2009 · Viewed 7.5k times · Source

I am trying to connect a simple groovy script to the DB.

Code:

import groovy.sql.Sql
class GroovySqlExample2{
  static void main(String[] args) {
    def sql = Sql.newInstance("jdbc:sqlserver://MYSERVERIP", "uname",
           "pwd", "net.sourceforge.jtds.jdbc.Driver")
    sql.eachRow("select * from word"){ 
      println it.spelling + " ${it.part_of_speech}"
    }
  }
}

I've placed jtds-1.2.3.jar inside C:\groovy-1.6.3\lib folder but the above code keeps complaining:

java.lang.ClassNotFoundException: net.sourceforge.jtds.jdbc.Driver

Answer

Jarek Przygódzki picture Jarek Przygódzki · Jul 21, 2014

Use Grape and set systemClassLoader=true

@Grapes(
    @Grab(group='net.sourceforge.jtds', module='jtds', version='1.3.1')
)
@GrabConfig(systemClassLoader=true)
import groovy.sql.*
// http://jtds.sourceforge.net/faq.html#urlFormat
def sql = Sql.newInstance("jdbc:jtds:sqlserver://MYSERVERIP", "uname",
       "pwd", "net.sourceforge.jtds.jdbc.Driver")
sql.eachRow("select * from word"){ 
  println it.spelling + " ${it.part_of_speech}"
}