Database Connection
To set up a connection to an external database, you need to know the following information for the database:
- The JDBC URL
- Any required credential information (username and password)
- The driver class
To set up an external database connection and make the database available to scripts:
Other Drivers
You might want to use these to create a custom field that allows users to pick from a row in a spreadsheet.
In the example shown below, we are using a CSV driver. This makes available all CSV in the directory provided in the JDBC URL. So in /tmp, we have a CSV file called devs.csv.
tomcat lib directory of your installation and restart. For example, this could be /opt/<application>/lib/.1 by default. This can potentially lead to multiple threads using the driver at the same time, leading to indeterministic behaviour and exceptions while using the CSV drivers. To prevent this from happening, you should set the connection pool size to 1. Set the following in the Additional Properties configuration field on the Database Connection resource configuration screen:maximumPoolSize=1
Use database connections in scripts
import com.onresolve.scriptrunner.db.DatabaseUtil
DatabaseUtil.withSql('local') { sql ->
sql.rows('select * from project')
}DatabaseUtil.withSql takes two arguments:
- The name of the connection as defined by you in the Pool Name parameter when adding the connection (in this example local),
- A closure. The closure receives an initialized
groovy.lang.Sqlobject as an argument. See executing SQL for more information on executing queries. The benefit of using a closure is that it is returned the connection to the pool after execution.Compare with the alternative method of executing a query.
withSql method returns whatever the closure returns. For example, you could get the number of projects using:import com.onresolve.scriptrunner.db.DatabaseUtil
def nProjects = DatabaseUtil.withSql('local') { sql ->
sql.firstRow('select count(*) from project')[0]
}You could also retrieve projects as follows:
Project objects for Project A.import com.onresolve.scriptrunner.db.DatabaseUtil
import com.atlassian.jira.project.Project
def projects = DatabaseUtil.withSql('local') { sql ->
sql.rows("select pkey from project where pname = 'Project A'").collect { row ->
Projects.getByKey(row.pkey as String)
}
} as List<Project>
projectsWe use the above script to query the database and collect the project keys, then use them to get the project objects.