topic description
The go-sql-driver/mysql
driver used by initializes the connection pool object in another package, and sets * sq;.DB
as a global variable to reference in another package, uses Query to get the MySQL connection, and the query keeps reporting errors?
related codes
package database
import (
"database/sql"
"fmt"
_ "github.com/go-sql-driver/mysql"
"log"
)
var Db *sql.DB
func init() {
var err error
Db, err = sql.Open("mysql", "root:123456@tcp(127.0.0.1:3306)/blog?charset=utf8")
if err != nil {
fmt.Println("conn failed!")
log.Fatal(err.Error())
}
defer Db.Close()
fmt.Println(&Db)
Db.SetMaxOpenConns(2000)
Db.SetMaxIdleConns(1000)
err = Db.Ping()
if err != nil {
log.Fatal(err.Error())
}
fmt.Println("db inti")
}
package controllers
import (
. "build-web-application/004-blog/database"
//"database/sql"
"fmt"
"github.com/gin-gonic/gin"
_ "github.com/go-sql-driver/mysql"
"log"
)
func GetPosts(c *gin.Context) {
rows, err := Db.Query(`SELECT * FROM t_post`)
if err != nil {
log.Fatal(err)
}
// defer rows.Close()
for rows.Next() {
var id int
var post string
err = rows.Scan(&id, &post)
fmt.Println(id)
fmt.Println(post)
}
}