GO链接MySql
代码
package main import ( "database/sql" "fmt" _ "github.com/go-sql-driver/mysql" ) //GO链接MySql var Db *sql.DB //连接池对象 func initDB() (err error) { dsn := "username:password@tcp(127.0.0.1:3306)/database?charset=utf8" db, err := sql.Open("mysql", dsn) if err != nil { return err } err = db.Ping() if err != nil { return err } //设置数据库连接池最大连接数 db.SetMaxOpenConns(10) //设置最大链接空闲数 db.SetMaxIdleConns(5) Db = db return nil } type User struct { Id int Name string Age int } func main() { err := initDB() if err != nil { fmt.Printf("初始化失败,错误%v\n", err) return } fmt.Println("数据库链接成功。") var u1 User sqlStr := "select Id,Name,Age from User where Id=?;" //执行 rowObj := Db.QueryRow(sqlStr, 1) //赋值并关闭链接(Scan方法) rowObj.Scan(&u1.Id, &u1.Name, &u1.Age) fmt.Printf("Id:%v;Name:%v;Age:%v;\n", u1.Id, u1.Name, u1.Age) }