Gorm is used with MySQL. Db.Save cannot insert data into the database.

Gorm is used with MySQL. Db.Save cannot insert data into the database

related codes

type Like struct {
    ID        int    `gorm:"primary_key"`
    Ip        string `gorm:"type:varchar(20);not null;index:ip_idx"`
    Ua        string `gorm:"type:varchar(256);not null;"`
    Title     string `gorm:"type:varchar(128);not null;index:title_idx"`
    CreatedAt time.Time
}

func CreateUa(c *gin.Context) {
    var like Like
    like = Like{Ip:c.PostForm("ip"),Ua:c.PostForm("ua"),Title:c.PostForm("title")}
    //db.Create(&like)
    db.Save(&like)
    c.JSON(http.StatusCreated, gin.H{
        "status": http.StatusCreated,
        "message": "Like record created successfully!",
        "LikeId": like.ID})
}

Database connection

var(
db *gorm.DB
err error
sqlConnection = "username:password.@(127.0.0.1:3309)/gotest?charset=utf8&parseTime=True&loc=Local"
)
db,err = gorm.Open("mysql",sqlConnection)
if err != nil{
    panic("failed to connect database")
}
defer db.Close()

perform POST operation

http://localhost:8080/v1/createua?ip="192.168.0.8"&ua="UU888"&title="This is 8th record"

execute the POST request. There are only the values of ID and CreateAt fields in the database, and the data of the other three fields are not inserted into the database

May.31,2021

  

I think the answers are all wrong. Save has the function of Create, that is, when ID does not exist, Create
will be called. The main problem is that the parameter is passed but not received. He also said:
"to execute a POST request, there are only values of ID and CreateAt fields in the database. The data of the other three fields are not inserted into the database "
indicates that the insertion is successful
, so here is the problem:
http://localhost:8080/v1/createua?ip="192.168.0.8"&ua="UU888"&title="This is 8th record"
this is a get request. If the landlord uses post to receive it, he will definitely not get the value

.
Menu