第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機(jī)立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何插入多行

如何插入多行

Go
皈依舞 2023-06-01 10:04:51
我實際上是 Go 的新手,所以想知道像這樣插入數(shù)據(jù)的最佳方式{    "moduleId":"M101",    "topicId":["tt","ee"]}在 MySQL 數(shù)據(jù)庫中使用 Gotype 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}預(yù)期的結(jié)果是將 JSON 數(shù)組添加到 MySQL 中。
查看完整描述

1 回答

?
慕神8447489

TA貢獻(xiàn)1780條經(jīng)驗 獲得超1個贊

您不能簡單地將數(shù)組插入數(shù)據(jù)庫。相反,您應(yīng)該循環(huán)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

}

這將在數(shù)據(jù)庫中為您提供的 JSON 創(chuàng)建 2 個條目。


|---------------------|------------------|------------------|

|      module_id      |     topic_id     |     added_by     |

|---------------------|------------------|------------------|

|          M101       |         tt       |     Harsh        |

|---------------------|------------------|------------------|

|          M101       |         ee       |     Harsh        |

|---------------------|------------------|------------------|

要獲取它們,只需查詢您的數(shù)據(jù)庫:


SELECT * FROM ModuleTopic WHERE module_id = M101;


查看完整回答
反對 回復(fù) 2023-06-01
  • 1 回答
  • 0 關(guān)注
  • 140 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號