SHA256
80 lines
1.8 KiB
Go
80 lines
1.8 KiB
Go
package main
|
|
|
|
import (
|
|
"database/sql"
|
|
"fmt"
|
|
"log"
|
|
|
|
_ "github.com/go-sql-driver/mysql"
|
|
)
|
|
|
|
func main() {
|
|
db, err := sql.Open("mysql", "root:ttx2011@tcp(db.freeicu.top:32000)/ashare?charset=utf8mb4")
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
defer db.Close()
|
|
|
|
// List tables
|
|
rows, _ := db.Query("SHOW TABLES")
|
|
defer rows.Close()
|
|
fmt.Println("=== Tables ===")
|
|
for rows.Next() {
|
|
var name string
|
|
rows.Scan(&name)
|
|
fmt.Println(" ", name)
|
|
}
|
|
|
|
// For each table, describe it and show sample
|
|
tables := []string{}
|
|
rows2, _ := db.Query("SHOW TABLES")
|
|
for rows2.Next() {
|
|
var name string
|
|
rows2.Scan(&name)
|
|
tables = append(tables, name)
|
|
}
|
|
rows2.Close()
|
|
|
|
for _, t := range tables {
|
|
fmt.Printf("\n=== DESCRIBE %s ===\n", t)
|
|
rows3, _ := db.Query(fmt.Sprintf("DESCRIBE %s", t))
|
|
cols3, _ := rows3.Columns()
|
|
fmt.Printf("%-20s %-30s %-5s %-5s\n", cols3[0], cols3[1], cols3[2], cols3[3])
|
|
for rows3.Next() {
|
|
var field, typ, null, key string
|
|
var def, extra sql.NullString
|
|
rows3.Scan(&field, &typ, &null, &key, &def, &extra)
|
|
fmt.Printf("%-20s %-30s %-5s %-5s\n", field, typ, null, key)
|
|
}
|
|
rows3.Close()
|
|
|
|
fmt.Printf("\n=== Sample %s (LIMIT 3) ===\n", t)
|
|
rows4, _ := db.Query(fmt.Sprintf("SELECT * FROM %s LIMIT 3", t))
|
|
cols4, _ := rows4.Columns()
|
|
fmt.Println(cols4)
|
|
for rows4.Next() {
|
|
vals := make([]interface{}, len(cols4))
|
|
ptrs := make([]interface{}, len(cols4))
|
|
for i := range vals {
|
|
ptrs[i] = &vals[i]
|
|
}
|
|
rows4.Scan(ptrs...)
|
|
for _, v := range vals {
|
|
switch vt := v.(type) {
|
|
case []byte:
|
|
fmt.Printf("%-20s", string(vt))
|
|
default:
|
|
fmt.Printf("%-20v", vt)
|
|
}
|
|
}
|
|
fmt.Println()
|
|
}
|
|
rows4.Close()
|
|
|
|
// Row count
|
|
var cnt int
|
|
db.QueryRow(fmt.Sprintf("SELECT COUNT(*) FROM %s", t)).Scan(&cnt)
|
|
fmt.Printf("Total rows: %d\n", cnt)
|
|
}
|
|
}
|