登录
首页 >  Golang >  Go问答

插入多行的方法

来源:stackoverflow

时间:2024-03-18 21:24:27 214浏览 收藏

在使用 Go 操作 MySQL 数据库时,将包含多个元素的数组插入数据库并非易事。为解决此问题,必须逐个遍历数组并逐个元素地将其插入数据库中。这将确保将数组中的所有元素都正确插入到数据库中,并避免任何数据丢失或损坏。

问题内容

我实际上对 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;

理论要掌握,实操不能落!以上关于《插入多行的方法》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>