我实际上是一个非常新的去,所以想知道最好的方法来插入这样的数据
{
"moduleId":"M101",
"topicId":["tt","ee"]
}
在mysql数据库中使用go
type TopicModule struct {
ModuleId string `json:"moduleId" bson:"moduleId" form:"moduleId"`
TopicId []string `json:"topicId" bson:"topicId" form:"topicId"`
AddedBy string `json:"addedBy" bson:"addedBy" form:"addedBy"`
}
func AddTopicModuleHandler(ctx iris.Context) {
topicmodule := new(TopicModule)
if err := ctx.ReadJSON(topicmodule); err != nil {
panic(err)
ctx.StatusCode(400)
return
}
log.Println(topicmodule.TopicId)
code, created := AddTopicModule(*topicmodule)
if created {
ctx.JSON(topicmodule)
ctx.Redirect("/api/module/"+code, iris.StatusCreated)
}
}
func AddTopicModule(atm TopicModule) (string, bool) {
log.Println("the topic is ", atm.TopicId)
db := DatabaseAccess()
tx, _ := db.Begin()
stmt, err := tx.Prepare("insert into ModuleTopic(module_id, topic_id, added_by) Values(?,?,?) ")
res, err := stmt.Exec(atm.ModuleId, "Ricky")
res1, err := stmt.Exec(atm.ModuleId, "Ric")
if err != nil {
tx.Rollback()
}
tx.Commit()
log.Println(res, res1)
return "aa", true
}
预期的结果是将json数组添加到mysql中。
1条答案
按热度按时间olqngx591#
不能简单地将数组插入数据库。相反,您应该在
TopicId
一个接一个地插进去这将在数据库中为您提供的json创建2个条目。
要获取它们,只需查询数据库: