Created
September 20, 2017 02:13
-
-
Save chaosx/3e81c8752deba00ecab07255d94619fe to your computer and use it in GitHub Desktop.
Golang MySQL select to json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| var ( | |
| dbhostsip = "10.10.12.2:3306" //IP地址 | |
| dbusername = "aogooc" //用户名 | |
| dbpassword = "123456" //密码 | |
| dbname = "ops" //表名 | |
| dbcharset = "utf8" | |
| ) | |
| func getConnString() string { | |
| return dbusername + ":" + dbpassword + "@tcp(" + dbhostsip + ")/" + dbname + "?charset=" + dbcharset | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "database/sql" | |
| "encoding/json" | |
| "log" | |
| // mysql pkg | |
| _ "github.com/go-sql-driver/mysql" | |
| ) | |
| func getJSON(sqlString string, taskID string) (string, error) { | |
| sqlConnString := getConnString() | |
| db, err := sql.Open("mysql", sqlConnString) | |
| if err != nil { | |
| return "", err | |
| } | |
| defer db.Close() | |
| rows, err := db.Query(sqlString, taskID) | |
| if err != nil { | |
| return "", err | |
| } | |
| 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 string(jsonData), nil | |
| } | |
| func main() { | |
| taskID = "1" | |
| sql := "select t2.address, t2.state, t2.description from wildebeest where id = ?" | |
| rows, err := getJSON(sql, taskID) | |
| log.Println(rows) | |
| log.Println(err) | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment