Golang Create tree from MySQL

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Golang Web develop always using the tree menu in our project.then so can be Reference resources.this article teach how T o Get tree menu in Web project.

1.show table of menu in MySQL database

```mysql> desc menu;+-------+-------------+------+-----+---------+-------+| Field | Type        | Null | Key | Default | Extra |+-------+-------------+------+-----+---------+-------+| id    | int(11)     | YES  |     | NULL    |       || name  | varchar(50) | YES  |     | NULL    |       || pid   | int(11)     | YES  |     | NULL    |       |+-------+-------------+------+-----+---------+-------+3 rows in set (0.00 sec)
```mysql> select * from menu;+------+------+------+| id   | name | pid  |+------+------+------+|    1 | aa   |    0 ||    2 | bb   |    1 ||    3 | cc   |    1 ||    4 | dd   |    2 ||    5 | ee   |    3 ||    6 | ee   |    4 |+------+------+------+6 rows in set (0.00 sec)```

2.base operation in golang,that include tree files thats call db.go/menu.go/main.go

db.gopackage modelimport (    "database/sql"    "fmt"    _ "github.com/go-sql-driver/mysql")var (    dbURL = "root:root@tcp(127.0.0.1:3306)/test?charset=utf8")func Tx(v_sql string, args ...interface{}) (*sql.Rows, error) {    db, err := sql.Open("mysql", dbURL)    defer db.Close()    stmt, err := db.Prepare(v_sql)    if err != nil {        fmt.Println("Tx err:", err)        return nil, err    }    return stmt.Query(args...)}
Menu.gopackage modelimport ("Database/sql" "FMT") const (querysql = "Select Id,name,pid from menu where pid =?") ) Type menu struct {curid int64 ' JSON: "Curid" ' Name string ' JSON: ' Name ' ' ParentID Int64 ' JSON: "Parent ID "' Child []*menu ' JSON:" Child,omitempty "'}func menuappend (M *menu) {fmt. Println (querysql) Child, err: = Menuinit (Querysql, M.curid) if err! = Nil {fmt.    Println ("Menuappend err:", err) return} M.child = Child for _, V: = Range M.child {menuappend (v) }}func LoadMenu () (*menu, error) {MS, Err: = Menuinit (querysql, 0) if err! = Nil {fmt. Println ("LoadMenu err:", err) return nil, err} root: = Ms[0] Menuappend (root) return root, Nil}func Me Nuinit (sql0 string, id Int64) ([]*menu, error) {rows, err: = Tx (sql0, id) if err! = Nil {fmt. Println ("Meneinit err:", err) return nil, err} MS: = Make ([]*menu, 0) for rows. Next () {m: = &menu{} var ID sql. NullInt64 var name sql. nullstring var pid sql. NullInt64 If Err = rows. Scan (&id, &name, &pid); Err! = Nil {fmt. PRINTLN ("Menuinit error:", err) return nil, err} if ID. Valid {M.curid = ID. Int64} if name. Valid {m.name = Name. String} if PID. Valid {m.parentid = pid. Int64} ms = Append (MS, m)} FMT. PRINTLN ("Current data:", MS) return MS, nil}
main.gopackage mainimport (    "encoding/json"    "fmt"    _ "github.com/go-sql-driver/mysql"    "model")func main() {    root, err := model.LoadMenu()    if err != nil {        fmt.Println("err:", err)    }    b, err := json.Marshal(root)    fmt.Println(string(b))}

3.run and get tree data from JSON

{  "curid": 1,   "name": "aa",   "parentid": 0,   "child": [    {      "curid": 2,       "name": "bb",       "parentid": 1,       "child": [        {          "curid": 4,           "name": "dd",           "parentid": 2,           "child": [            {              "curid": 6,               "name": "ee",               "parentid": 4            }          ]        }      ]    },     {      "curid": 3,       "name": "cc",       "parentid": 1,       "child": [        {          "curid": 5,           "name": "ee",           "parentid": 3        }      ]    }  ]}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.