Get JSON data directly from rows loop without scanning in Golang

Viewed 49

I have a function that processes a database query and return the rows. I'm using rows.Next() function to loop and scan each row. For that I'm using rows.Scan() function. Here is my code snippet.

tsql := "SELECT * from Users;"

// Execute query
rows, err := db.QueryContext(ctx, tsql)
if err != nil {
    return -1, err
}

defer rows.Close()

// Iterate through the result set.
for rows.Next() {
    var name, location string
    var id int

    //Get values from row.
    err := rows.Scan(&id, &name, &location)
    if err != nil {
        return -1, err
    }

    fmt.Printf("ID: %d, Name: %s, Location: %s\n", id, name, location)
}

Is there a way to get each row data in JSON format without scanning? Thank you

1 Answers

Using the below query will give the output as JSON,

 SELECT * from Users FOR JSON AUTO;
Related