Skip to content
TheChatArchiveThe Chat Archive
gpt-3.5-turbo-0613· openaiHugging Face Suzhen/CodeChat

groovy script to return resultset

  1. User

    groovy script to return resultset

  2. 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.Sql class to connect to a database using JDBC. We define the database connection URL, the SQL query, and execute the query using the rows method of the Sql object. The result set is stored in a List of Map objects, 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 close method of the Sql object. 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.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.