How to define database 'driver' using Groovy sql module - groovy

I am trying to connect to an Oracle Sql Developer DB using Groovys sql class, which requires 4 pieces of information: (db url, username, password, db driver) I have all information needed except the driver. I have tried using oracle.jdbc.driver.OracleDrive and have set my GROOVY_HOME as : Variable: %GROOVY_HOME%\lib Value: C:\Oracle_SQL_DEVELOPER\sqldeveloper
I am receiving the following error :
Caused by: java.lang.ClassNotFoundException: oracle.jdbc.driver.OracleDriver
I have referenced a few answers here on StackOverflow but haven't had any luck setting up a connection. Here are the links I've read and tried:
Unable to connect to oracle database from groovy
SQLException: No suitable Driver Found for jdbc:oracle:thin:#//localhost:1521/orcl
I have also looked and researched the Groovy documentation but it is not clear on how to define the driver: https://groovy-lang.org/databases.html#_connecting_with_a_datasource
Any help would be much appreciated. Here is the code for reference:
import groovy.sql.Sql
class EstablishConnection {
def static url = 'url'
def static user = 'user'
def static password = 'pass'
def static driver = 'oracle.jdbc.driver.OracleDriver'
def static sql = Sql.newInstance(url, user, password, driver)
}
EstablishConnection.sql.eachRow('select * from ACCOUNT where CONSTI_ID = \'12345678\';'){
row ->
def a = row[0]
}

Related

django-viewflow, rest api saving foreign key says "<ProcessName> has no <ForeignModel>"

I have the following models setup:
class Cluster(models.Model):
name = models.CharField(...)
...
class ResourceRequest(Process):
cluster = models.ForeignKey('Cluster')
def clean(self, ...):
if self.cluster.name == 'abc':
...
And when I try to post to:
http://pmas-local:8000/workflow/api/tasks/vm_request/resourcerequest/start/
it complains that ResourceRequest has no cluster.
Stacktrace shows if self.cluster.name == 'abc': caused the problem.
The error is not related to django-viewflow. That's standard django error for a foreign key field, which means that self.cluster is None.

getDatabaseConnectionByName returns PASS_VALUE instead of actual db password from environment

I am working on a project where we have multiple environments and for each environment we have a separate database connection string which I have added in environments section.
Now I want to get the environment connection string at runtime using Groovy test step to use it further to execute query. Below is my script:
def connectionString = context.testCase.testSuite.project.activeEnvironment.databaseConnectionContainer.getDatabaseConnectionByName("dbconnection").getConnectionString()
Now in response I am getting connection error as I can see in response the script is returning jdbc:oracle:thin:Username/PASS_VALUE#machine details. As per my understanding the PASS_VALUE is causing this issue.
com.eviware.soapui.support.GroovyUtils.registerJdbcDriver( "oracle.jdbc.driver.OracleDriver" )
import groovy.sql.Sql;
//get active environment connection string
def connectionString = context.testCase.testSuite.pro
log.info ("Connection String#####"+connectionString)
def driver="oracle.jdbc.driver.OracleDriver";
def con = Sql.newInstance(connectionString,driver);
So this getConnectionString() should return the password so that it can be used in further script.

Pentaho data source access from Groovy

In Pentaho Report Designer (PRD), I want to connect to my Data source using a Groovy script (or EMCAScript script) by referring to JNDI created in default.properties file. So, I will create a mult-value list parameter containing JNDI names and connect to the data source based on the JNDI selected in the parameter.
Script:
import groovy.sql.Sql
import javax.naming.InitialContext
import javax.sql.DataSource
class SqlClient {
InitialContext context = new InitialContext()
DataSource dataSource = context.lookup("OLTP") as DataSource
def sql = new Sql(dataSource)
sql.execute("SELECT * FROM Person.User_JNDI")
TypedTableModel model = new TypedTableModel();
while(sql.next())
model.addRow(new Object [] {rs.getString(1)});
c.close();
return model;
}
I am getting the following error:
Caused by: org.apache.bsf.BSFException: exception from Groovy: org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
expression: 11: unexpected token: sql # line 11, column 5.
sql.execute("SELECT * FROM Person.User_JNDI")
Also, PRD expects the script to return a model, probably something to do with TypedtableModel class.
Can anyone give me an example of Groovy script?
Assuming that you have filled the default.properties as it says here, you should be able to access the data source with something like:
import groovy.sql.Sql
import javax.naming.InitialContext
import javax.sql.DataSource
class SqlClient {
InitialContext context = new InitialContext()
DataSource dataSource = context.lookup("SampleData") as DataSource
def sql = new Sql(dataSource)
sql.execute '''
select * from ... '''
...
}
Using a Sql instance.

groovy script classpath

I'm writing a script in Groovy and I would like someone to be able to execute it simply by running ./myscript.groovy. However, this script requires a 3rd party library (MySQL JDBC), and I don't know of any way to provide this to the script other than via a -classpath or -cp argument, e.g.
`./monitor-vouchers.groovy -cp /path/to/mysql-lib.jar`
For reasons I won't go into here, it's not actually possible to provide the JAR location to the script using the -classpath/-cp argument. Is there some way that I can load the JAR from within the script itself? I tried using #Grab
import groovy.sql.Sql
#Grab(group='mysql', module='mysql-connector-java', version='5.1.19')
def getConnection() {
def dbUrl = 'jdbc:mysql://database1.c5vveqm7rqgx.eu-west-1.rds.amazonaws.com:3306/vouchers_prod'
def dbUser = 'pucaroot'
def dbPassword = 'password'
def driverClass = "com.mysql.jdbc.Driver"
return Sql.newInstance(dbUrl, dbUser, dbPassword, driverClass)
}
getConnection().class
But this causes the following error:
Caught: java.sql.SQLException: No suitable driver
java.sql.SQLException: No suitable driver
at monitor-vouchers.getConnection(monitor-vouchers.groovy:13)
at monitor-vouchers.run(monitor-vouchers.groovy:17)
Is there a way I can execute this script using just ./monitor-vouchers.groovy
You should be able to do:
import groovy.sql.Sql
#GrabConfig(systemClassLoader=true)
#Grab('mysql:mysql-connector-java:5.1.19')
def getConnection() {
def dbUrl = 'jdbc:mysql://database1.c5vveqm7rqgx.eu-west-1.rds.amazonaws.com:3306/vouchers_prod'
def dbUser = 'pucaroot'
def dbPassword = 'bigsecret'
def driverClass = "com.mysql.jdbc.Driver"
return Sql.newInstance(dbUrl, dbUser, dbPassword, driverClass)
}
getConnection().class
Two more options:
Put the jar in ${user.home}/.groovy/lib
If the jar is in a known location, use this code to load it into the current class loader:
this.class.classLoader.rootLoader.addURL( new URL() )

Groovy: How to access to the values already set in DataSource

I have a groovy application which is using an Oracle DB as DataSource.
In DataSource.groovy I've set:
dataSource {
pooled = true
driverClassName = "oracle.jdbc.driver.OracleDriver"
username = "scott"
password = "tiger
//loggingSql = true
}
For some performance reasons at some points I am accesing the DB using sql in the following way:
def sql = Sql.newInstance("jdbc:oracle:thin:#localhost:1521:XE", "scott", "tiger", "oracle.jdbc.driver.OracleDriver")
That is, username and password are hardwired twice in the application.
My question is if it possible to address in my application to the attributes username and password already set in the DataSource.groovy.
Thanks in advance,
Luis
The solution is to add some imports
import javax.sql.DataSource
import groovy.sql.Sql
import org.codehaus.groovy.grails.commons.ConfigurationHolder
and the following code:
def _url = ConfigurationHolder.config.dataSource.url
def _username = ConfigurationHolder.config.dataSource.username
def _password = ConfigurationHolder.config.dataSource.password
def _driver = ConfigurationHolder.config.dataSource.driverClassName
def sql = Sql.newInstance(_url, _username, _password, _driver)
def query = "<your SQL query>"
sql.eachRow(query){
println "ID: " + it.id // Whatever you need
}
You may create Sql class by datasource, for example
def sql = new Sql(myDataSource)
where myDataSource - object of class DataSource (you can get your DS declared in DataSource.groovy)
Can't you just do the following? (assuming that dataSource is a variable in scope)
def sql = Sql.newInstance("jdbc:oracle:thin:#localhost:1521:XE", dataSource.username, dataSource.password, dataSource.driverClassName)

Resources