https://github.com/rogozhka/query
Tiny Go package to fetch SQL rows as a slice of map[string]string
https://github.com/rogozhka/query
golang-library mysql sql
Last synced: about 1 year ago
JSON representation
Tiny Go package to fetch SQL rows as a slice of map[string]string
- Host: GitHub
- URL: https://github.com/rogozhka/query
- Owner: rogozhka
- License: mit
- Created: 2018-01-26T21:32:13.000Z (about 8 years ago)
- Default Branch: master
- Last Pushed: 2022-11-28T19:51:06.000Z (over 3 years ago)
- Last Synced: 2025-01-02T06:19:16.111Z (over 1 year ago)
- Topics: golang-library, mysql, sql
- Language: Go
- Homepage:
- Size: 26.4 KB
- Stars: 1
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
**Query** is a tiny package for executing select-like queries and converting `sql.Rows` into slice of `map[string]string`. The new map is allocated for each row. Keys are column names as seen in sql.
## Install
Use go modules and just
```
import "github.com/rogozhka/query"
```
or
```bash
go get -u github.com/rogozhka/query
```
## Example
```go
package main
import (
"github.com/rogozhka/query"
"database/sql"
"fmt"
"log"
_ "github.com/go-sql-driver/mysql"
)
func main() {
db, err := sql.Open("mysql",
"username:pass@tcp(hostname)/database_name")
if err != nil {
panic(err)
}
if db == nil {
panic(fmt.Errorf("db is nil"))
}
defer db.Close()
// fetch all the rows into slice of map[string]string
rows, err := query.Fetch("SELECT * FROM `example_table`", db)
if err != nil {
panic(err)
}
for _, row := range rows {
for colName, val := range row {
log.Printf("%s:%s", colName, val)
}
}
// fetch only 1 row
// in real project you should use LIMIT 0,1
// but there is limited version of method ;)
rows2, err := query.FetchLimited("SELECT * FROM `example_table`", 1, db)
if err != nil {
panic(err)
}
if len(rows2) > 0 {
for colName, val := range rows2[0] {
log.Printf("%s:%s", colName, val)
}
}
}
```