Skip to content

Instantly share code, notes, and snippets.

@joaofnds
Last active January 3, 2018 09:30
Show Gist options
  • Save joaofnds/1ff2fc2868aedfa74b7be3dd1a624f2f to your computer and use it in GitHub Desktop.
Save joaofnds/1ff2fc2868aedfa74b7be3dd1a624f2f to your computer and use it in GitHub Desktop.
Performs a SQL "DESCRIBE database;" command in go using the database/sql and go-sql-driver/mysql packages
package main
import (
"database/sql"
"encoding/json"
"fmt"
"log"
_ "github.com/go-sql-driver/mysql"
)
var (
db *sql.DB
)
// Field contains the field of a SQL database description
type Field struct {
Field string `json:"field,omitempty"`
Type string `json:"type,omitempty"`
Null string `json:"null,omitempty"`
Key string `json:"key,omitempty"`
Defauls []byte `json:"defaults"`
Extra string `json:"extra,omitempty"`
}
func init() {
var err error
db, err = sql.Open("mysql", "root:root@tcp(localhost:3306)/root")
checkErr(err)
checkErr(db.Ping())
}
func main() {
defer db.Close()
rows, err := db.Query("DESCRIBE root")
checkErr(err)
defer rows.Close()
fields := make([]Field, 0)
f := Field{}
for rows.Next() {
checkErr(rows.Scan(
&f.Field,
&f.Type,
&f.Null,
&f.Key,
&f.Defauls,
&f.Extra,
))
fields = append(fields, f)
}
j, err := json.Marshal(fields)
checkErr(err)
fmt.Print(string(j))
}
func checkErr(e error) {
if e != nil {
log.Fatal(e)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment