gpt4 book ai didi

python - PyMySQL executemany with ON DUPLICATE

转载 作者:可可西里 更新时间:2023-11-01 07:08:49 35 4
gpt4 key购买 nike

我有一个由名为 member 的字典组成的列表,我像这样插入到数据库中

    # Executes query for each dictionary in member.
cursor.executemany("INSERT INTO `Citizens` (`Handle`,`Org`,`Role`, "
"`Rank`,`Visibility`,`Stars`,`Type`) VALUES "
"(%(handle)s,%(sid)s,%(roles)s,%(rank)s,"
"%(visibility)s,%(stars)s,%(type)s)", member)
# Commits changes to the database.
conn.commit()

它工作得很好,但是当我开始遇到重复成员的问题时,我决定添加一个 ON DUPLICATE 子句。这个想法是,如果一个成员是重复的,我们希望通过连接新数据来更新他的 Org 列。所以我把代码改成这样

    # Executes query for each dictionary in member.
cursor.executemany("INSERT INTO `Citizens` (`Handle`,`Org`,`Role`, "
"`Rank`,`Visibility`,`Stars`,`Type`) VALUES "
"(%(handle)s,%(sid)s,%(roles)s,%(rank)s,"
"%(visibility)s,%(stars)s,%(type)s) ON DUPLICATE"
" KEY UPDATE `Org`=concat(ifnull(`Org`, \"\"), "
"\", \", %(sid)s);", member)
# Commits changes to the database.
conn.commit()

但是在这样做时我得到了以下错误:

There was a problem inserting member(s): (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '('real_lethality','000',0,'Master','visible',5,'affiliate') ON DUPLICATE KEY UPD' at line 3")
Would you like to see the failed SQL query?[Y/n]
b'INSERT INTO `Citizens` (`Handle`,`Org`,`Role`, `Rank`,`Visibility`,`Stars`,`Type`) VALUES \n(\'fullmetaljim\',\'000\',\'Founder\',\'Master\',\'visible\',5,\'main\') ON DUPLICATE KEY UPDATE `Org`=concat(ifnull(`Org`, ""), ", ", \'000\'),\n(\'real_lethality\',\'000\',0,\'Master\',\'visible\',5,\'affiliate\') ON DUPLICATE KEY UPDATE `Org`=concat(ifnull(`Org`, ""), ", ", \'000\')\n;'

我是否错误地实现了ON DUPLICATE?我怎样才能使它正常工作?

示例成员:

[
{'roles': [],
'rank': 'No SCB account',
'type': 'main',
'stars': 2,
'visibility': 'visible',
'sid': 'imperium',
'handle': 'freakyeagle'
},
{'roles': [],
'rank': 'Fleet Member',
'type': 'main',
'stars': 1,
'visibility': 'visible',
'sid': 'imperium',
'handle': 'cadimus'},
{'roles': [],
'rank': 'Fleet Member',
'type': 'main',
'stars': 1,
'visibility': 'visible',
'sid': 'imperium',
'handle': 'belleal'}
]

编辑:看来这可能是 PyMySQL 本身的错误,有人能证实吗?

最佳答案

查看您的代码和错误查询,我同意 executemany 方法构造的查询不正确。我建议您以更手动的方式构建插入,循环遍历参数,并在没有 executemany 方法的情况下执行它。

此外,MySQL AFAIK 完全可以使用单引号,因此如果您将查询放在双引号中,请使用单引号作为内部字符串限定符 - 这样您就不需要一直转义。

关于python - PyMySQL executemany with ON DUPLICATE,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33785011/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com