Skip to content

Instantly share code, notes, and snippets.

@jakobii
Created November 1, 2019 22:40
Show Gist options
  • Save jakobii/864237b722f81cd70b3f48e54588cb66 to your computer and use it in GitHub Desktop.
Save jakobii/864237b722f81cd70b3f48e54588cb66 to your computer and use it in GitHub Desktop.
package main
import (
"database/sql"
"encoding/json"
"fmt"
"log"
_ "github.com/denisenkom/go-mssqldb"
)
// Query runs sql queries
func Query(q string) ([]map[string]interface{}, error) {
db, err := sql.Open("sqlserver", `sqlserver://USERNAME:PASSWORD@SERVER?database=DATABASE&TrustServerCertificate=true`)
if err != nil {
return nil, err
}
defer db.Close()
rows, err := db.Query(q)
if err != nil {
return nil, err
}
defer rows.Close()
columns, err := rows.ColumnTypes()
if err != nil {
// there are no columns
return nil, nil
}
vals := make([]interface{}, len(columns))
Ptrs := make([]interface{}, len(columns))
for i := range vals {
Ptrs[i] = &vals[i]
}
row := make(map[string]interface{})
results := make([]map[string]interface{}, 0)
for rows.Next() {
err = rows.Scan(Ptrs...)
for i := 0; i < len(columns); i++ {
row[columns[i].Name()] = vals[i]
}
results = append(results, row)
}
err = rows.Err()
if err != nil {
log.Fatal(err)
}
return results, err
}
func main() {
rows, err := Query("select top 2 * from Employees")
if err != nil {
log.Fatal(err)
}
//fmt.Println(rows)
results, err := json.Marshal(rows)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(results))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment