groovy script to return resultset
- User
groovy script to return resultset
- Assistant
Here's an example of a Groovy script that connects to a database using JDBC and returns the result set:
@Grab('com.h2database:h2:1.4.200') import groovy.sql.Sql // Create a connection string for the database def url = 'jdbc:h2:mem:test;DB_CLOSE_DELAY=-1' // Define the SQL query def query = 'SELECT * FROM my_table' // Open a connection to the database def sql = Sql.newInstance(url, 'sa', '', 'org.h2.Driver') // Execute the query and get the result set def result = sql.rows(query) // Iterate over the result set and print the values result.each { row -> println "ID: ${row.ID}, Name: ${row.Name}, Age: ${row.Age}" } // Close the connection sql.close()In this example, we use the
groovy.sql.Sqlclass to connect to a database using JDBC. We define the database connection URL, the SQL query, and execute the query using therowsmethod of theSqlobject. The result set is stored in aListofMapobjects, where each map represents a row in the result set.We then iterate over the result set and print the values for each row. Finally, we close the database connection using the
closemethod of theSqlobject. In this example, we are using an in-memory H2 database, but you can modify the connection URL to connect to any other supported database.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.