golang mysql为什么这个删除不能正常工作与mysql的IN条件

eanckbw9  于 2023-06-27  发布在  Go
关注(0)|答案(2)|浏览(111)

我使用golang mysql来执行delete语句
删除的目标是使用IN条件,但只删除一条记录。是什么造成的?

go 1.16
import (
    "database/sql"
    "errors"
    "fmt"
    "io"
    "log"
    "net/http"
    "strconv"
    "strings"
    "time"

    "github.com/aws/aws-lambda-go/events"
    "github.com/aws/aws-lambda-go/lambda"

    // "github.com/leekchan/timeutil"
    _ "github.com/go-sql-driver/mysql" //v1.7.1
)
func SelectQuery(action string, schema string) string {
    if action == "del" {
        switch schema {
        case "schema1":
            return "DELETE FROM `schema1` WHERE `id` IN (?)"
        default:
            panic("bad request")
        }
    } 
}
func DelAction(db *sql.DB, schema string, list []int) int64 {
    strList := []string{} 
    for _, v := range list { // this is id list ex.[1, 2, 3]
        strList = append(strList, strconv.Itoa(v))
    }
    delQeury := SelectQuery("del", schema) // "DELETE FROM `schema1` WHERE `id` IN (?)"
    param := strings.Join(strList, ",") // param: 1,2,3
    delRes, err := db.Exec(delQeury, param)
    delCnt, err := delRes.RowsAffected()
    return delCnt // delete only 1 records. even if param have 3 values
}

我想删除所有3条记录,但只删除了1条记录
add info创建一个ID int slices的数组,并删除。例如[1、2、3]

res, err := db.Query(query) // select query

    list := []int{}
    for res.Next() {
        u := &Logs{} // type logs is id int 
        if err := res.Scan(&u.id); err != nil {
            fmt.Println("scan error")
            panic(err.Error())
        } else {
            list = append(list, u.id)
        }
    }
kmb7vmvb

kmb7vmvb1#

这解决了它。我不知道这是不是最好的方法,但它是这样工作的。

args := []interface{}{}
    for _, x := range list {
        args = append(args, x)
    }
    stmt := `DELETE FROM schema WHERE id IN (?` + strings.Repeat(", ?", len(list)-1) + `)`
db.Exec(stmt, args...)
a2mppw5e

a2mppw5e2#

问号仅表示一个参数,而不是参数列表。传递的参数列表将被转换为它的字符串表示形式,然后被截断。
下面是纯SQL中的等价物:

CREATE TABLE t1 (a int);
INSERT INTO t1 VALUES (1),(2),(3);
DELETE FROM t1 WHERE a in ("1,2,3");
Query OK, 1 row affected, 1 warning (0,009 sec)
SHOW WARNINGS;
+---------+------+--------------------------------------------+
| Level   | Code | Message                                    |
+---------+------+--------------------------------------------+
| Warning | 1292 | Truncated incorrect DECIMAL value: '1,2,3' |
+---------+------+--------------------------------------------+
1 row in set (0,001 sec)
SELECT a FROM t1;
+------+
| a    |
+------+
|    2 |
|    3 |
+------+
2 rows in set (0,001 sec)

我建议在go中构建整个SQL语句而不带参数。在Python中,你会使用execute_many方法(),我不知道go是否提供类似的东西。

相关问题