如何从多个表中删除记录

我正在创建一个脚本,该脚本旨在将参数传递给 MySQL 查询,然后执行该 MySQL 查询以从多个表中删除多个记录。


现在我遇到了一个问题,我需要为每个单独的表创建多个文件。有没有一种方法可以在一个文件中执行每个 MySQL 查询,而不是为每个查询创建多个文件?


这是我创建的代码:


import (

"fmt"

"database/sql"

"os"

)


func DeleteTables() {

   fmt.Println("Test for MySQL")


   db, _ := sql.Open(

       "mysql", "user:password@(localhost:port)/db")


   args := os.Args

   if len(args) < 2 {

       fmt.Println("Supply a ID")

       os.Exit(1)

   }

   id := os.Args[1]

   fmt.Println(id)


   delete, err := db.Query("DELETE * FROM table1 WHERE id = ?;", id)


   if err != nil {

       panic(err.Error())

   }

   defer delete.Close()

}


慕妹3242003
浏览 99回答 1
1回答

墨色风雨

使用 for 循环为多个表提交 DELETE 语句。如果表名是固定的,请使用以下内容:for _,table:= range []string{"table1","table2","table3"} {&nbsp; &nbsp;_, err := db.Exec(fmt.Sprintf("DELETE * FROM %s WHERE id = ?;",table), id)&nbsp; &nbsp;if err != nil {&nbsp; &nbsp; &nbsp; &nbsp;panic(err.Error())&nbsp; &nbsp;}}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go