[英]How to insert multiple rows
我實際上對 Go 很陌生,所以想知道插入這樣的數據的最佳方法
{
"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 中。
您不能簡單地將數組插入到數據庫中。 相反,您應該循環使用TopicId
並將它們一一插入
func AddTopicModule(atm TopicModule) (string, bool) {
log.Println("the topic is ", atm.TopicId)
db := DatabaseAccess()
tx, _ := db.Begin()
for _, value = range(atm.TopicId){
stmt, err := tx.Prepare("insert into ModuleTopic(module_id, topic_id, added_by) Values(?,?,?) ")
if err != nil {
return "", false
}
res, err := stmt.Exec(atm.ModuleId, value, "Harsh")
if err != nil {
tx.Rollback()
return "", false
}
tx.Commit()
}
return "aa", true
}
這將在數據庫中為您提供的 JSON 創建 2 個條目。
|---------------------|------------------|------------------|
| module_id | topic_id | added_by |
|---------------------|------------------|------------------|
| M101 | tt | Harsh |
|---------------------|------------------|------------------|
| M101 | ee | Harsh |
|---------------------|------------------|------------------|
要獲取它們,只需查詢您的數據庫:
SELECT * FROM ModuleTopic WHERE module_id = M101;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.