如何用golang把mysql的資料傳輸到web上

chenyuan0922 · · 629 次点击
<a href="/user/didadi" title="@didadi">@didadi</a> 想請教一下,整體的流程嗎? 希望能有個較完整程式碼 感謝~
#4
更多评论
自己用golang 写一个server,然后用数据库查询值,然后返回给前端不就可以了?
#1
package main import ( //&#34;html/template&#34; //&#34;strings&#34; &#34;log&#34; &#34;net/http&#34; &#34;fmt&#34; &#34;database/sql&#34; _ &#34;github.com/go-sql-driver/mysql&#34; ) var ( t , i int array[]string v string c map[int]data base []data = make([]data,0) ) type data struct{ uid string username string departname string created string } func main() { fmt.Println(&#34;connect success&#34;) db, err := sql.Open(&#34;mysql&#34;, &#34;root:12345@tcp(127.0.0.1:3306)/123&#34;)//用户:密码@主机/数据库 checkErr(err) defer db.Close() i=0 rows, err := db.Query(&#34;SELECT * FROM userinfo&#34;) checkErr(err) for rows.Next() { var uid, username, department, created string err = rows.Scan(&amp;uid, &amp;username, &amp;department, &amp;created) checkErr(err) c = make(map[int]data) c[i] = data{uid, username, department, created} fmt.Println(c[i]) } http.HandleFunc(&#34;/&#34;,index) log.Println(&#34;Start&#34;) err1 :=http.ListenAndServe(&#34;:9090&#34;, nil) if err1!=nil { log.Fatal(&#34;ListenAndServe:&#34;, err1) } } func index(w http.ResponseWriter, r *http.Request) { db, err := sql.Open(&#34;mysql&#34;, &#34;root:123456789@tcp(127.0.0.1:3306)/123&#34;)//用户:密码@主机/数据库 checkErr(err) defer db.Close() rows, err := db.Query(&#34;SELECT * FROM userinfo&#34;) checkErr(err) for rows.Next(){ data := data{} err = rows.Scan(&amp;data.uid, &amp;data.username, &amp;data.departname, &amp;data.created) checkErr(err) base = append(base, data) } fmt.Fprintf(w,&#34;%s&#34;, base) } func checkErr(err error) { if err != nil { panic(err) } } 這是目前的程式碼 在web上輸出的是 [{1 andy a01 2018-07-05} {2 bob b01 2018-07-04} {3 couch c01 2018-07-03} {5 astaxie software developement 2012-12-09} {6 lin y c so tired 2018-07-05} {7 lin y c so tired 2018-07-05} {8 dean go is too hard to learn 2018-07-05} {9 sour2015 welcome to golang world 2018-07-11} {11 atm dont forget to eat lunch 2018-07-11} {12 atm dont forget to eat lunch 2018-07-11} {17 atm zxczqws 2017-01-12}] 無分行 希望是能夠放入一個表單中,看起來比較整潔
#2