问题遇到的现象和发生背景
使用golang开发交互mysql数据库,然后调用方法报错500
看了好多教程都没找到准确修改的方法,qq看看
遇到的现象和发生背景,请写出第一个错误信息
runtime error: invalid memory address or nil pointer dereference
方法
package myfunc8
import (
"database/sql"
"github.com/gin-gonic/gin"
"log"
"strconv"
"time"
)
type Course struct {
Cid int
Cname string
Tid int
}
func TestDB(dsn string) (db *sql.DB) {
db, err := sql.Open("mysql", dsn)
if err != nil {
return nil
}
db.SetConnMaxLifetime(time.Minute * 3)
db.SetMaxOpenConns(20)
db.SetMaxIdleConns(10)
return db
}
func QueryRowsHandler(g *gin.Context) {
cid, err := strconv.Atoi(g.Query("cid"))
if err != nil {
log.Println(err)
}
dsn := "root:root@/db"
db := TestDB(dsn)
courses := QueryRows(db, cid)
g.JSON(200, courses)
}
func QueryRows(db *sql.DB, cid int) []Course {
db.Begin()
RowsObj, err := db.Query("select cid,tid,cname from course where cid>?", cid)
if err != nil {
log.Println(err)
}
var courses []Course
for RowsObj.Next() {
var course Course
RowsObj.Scan(&course.Cid, &course.Cname, &course.Tid)
courses = append(courses, course)
}
return courses
}
主函数
```go
package main
import (
"github.com/gin-gonic/gin"
"go_gin_exercise/part08/myfunc8"
)
func main() {
g := gin.Default()
g.GET("/queryrows", myfunc8.QueryRowsHandler)
g.Run()
}
```