Skip to content

Instantly share code, notes, and snippets.

@YCF
Created March 2, 2017 11:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save YCF/e8519c39f9dd83e383f7c38a16f38890 to your computer and use it in GitHub Desktop.
Save YCF/e8519c39f9dd83e383f7c38a16f38890 to your computer and use it in GitHub Desktop.
查询数据库输出为json的例子
package main
import (
"database/sql"
"encoding/json"
"fmt"
"net/http"
"strings"
"github.com/go-ini/ini"
"github.com/labstack/echo"
_ "github.com/mattn/go-sqlite3"
)
func GetOption(section string, key string) (conf string) {
cfg, err := ini.InsensitiveLoad("./conf.ini")
conf = cfg.Section(section).Key(key).String()
if err != nil {
fmt.Println(err)
}
return conf
}
func main() {
e := echo.New()
e.GET("/sqlite/:query", func(c echo.Context) error {
dbSource := GetOption("Database", "Sqlite")
db, _ := sql.Open("sqlite3", dbSource)
if c.Param("query") == "" {
return c.String(http.StatusOK, "no query")
}
q := c.Param("query")
qStr := GetOption("Query", q)
if qStr == "" {
return c.String(http.StatusOK, "no query")
}
stmt, err := db.Prepare(qStr)
if err != nil {
return err
}
defer stmt.Close()
rows, err := stmt.Query()
if err != nil {
return err
}
defer rows.Close()
columns, err := rows.Columns()
if err != nil {
return err
}
count := len(columns)
tableData := make([]map[string]interface{}, 0)
values := make([]interface{}, count)
valuePtrs := make([]interface{}, count)
for rows.Next() {
for i := 0; i < count; i++ {
valuePtrs[i] = &values[i]
}
rows.Scan(valuePtrs...)
entry := make(map[string]interface{})
for i, col := range columns {
var v interface{}
val := values[i]
b, ok := val.([]byte)
if ok {
v = string(b)
} else {
v = val
}
entry[col] = v
}
tableData = append(tableData, entry)
}
jsonData, err := json.Marshal(tableData)
if err != nil {
return err
}
return c.String(http.StatusOK, string(jsonData))
})
e.Logger.Fatal(e.Start(":1323"))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment