先要下载驱动包,放到$GOPATH/src目录里: https://github.com/Go-SQL-Driver/MySQL
数据库:test 表:user 字段:id,name,view
package main import ( "database/sql" "fmt" _ "github.com/go-sql-driver/mysql" "log" ) var ( //db *sql.DB dbhostsip = "127.0.0.1:3306" dbusername = "root" dbpassowrd = "root" dbname = "test" ) func mysql_open() *sql.DB { Odb, err := sql.Open("mysql", dbusername+":"+dbpassowrd+"@tcp("+dbhostsip+")/"+dbname) if err != nil { log.Fatalln(err) fmt.Println("链接失败") return nil } //defer Odb.Close() fmt.Println("链接成功") return Odb } func mysql_select(db *sql.DB, data string) { rows, err := db.Query("select * from user") //fmt.Println(db) if err != nil { log.Fatalln(err) } //fmt.Println(rows) for rows.Next() { var id string var name string var view string err = rows.Scan(&id, &name, &view) //checkErr(err) fmt.Println("content:", id, name, view) //fmt.Println(open_send) //fmt.Println(cms_send) //fmt.Println(time) } } func main() { db := mysql_open() err := db.Ping() if err != nil { log.Fatal(err) } mysql_select(db, "select * from user") }
附件:源代码下载