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;
推荐阅读
- ios - Swift 5:给定的数据不是有效的 JSON(从 API 加载数据到表视图)
- javascript - Javascript 调整
- php - 使用 mysql 和 php 更新
- apache-kafka - Nifi ConsumeKafka 获取/轮询查询
- python - 如何在python中将列表列表的元素与列表的另一个元素列表分配
- python - ChromeDriver 已崩溃
- sql - 按日期范围 SQL Server 对结果进行排序
- javascript - 将对象数组转换为按值分组的数组数组
- android - 创建新片段时,无法识别相关的 XML 文件
- python - Python - 循环上的多个实例