【问题标题】:How to insert a string list in a python MySQLDB VALUE clause如何在 python MySQLDB VALUE 子句中插入字符串列表
【发布时间】:2020-07-15 11:54:37
【问题描述】:

这与imploding a list for use in a python MySQLDB IN clausepython list in sql query as parameter类似,但它们的列表元素都是整数。

param = []
param.append(post.title)
param.append(post.count_vote)
param.append(post.last_reply_time)
param.append(post.last_replyer_id)
param.append(post.poster_id)
param.append(post.content)
param.append(post.plain_content)
param.append(post.relate_unit)

query = "INSERT INTO post (title, countVote, lastReplyTime, lastReplyerId, posterId, content, plainContent, relateUnit) VALUES ('{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}', '{7}');".format(*param)

cursor.execute(query)

元素有多种类型,例如 int、str 和 None。让我印象深刻的是字符串类型,字符串可能包含'"。我之前只是简单地将' 替换为"。但是,我偶然在内容字段中看到了一些 C 代码 sn-p,例如 char ch = 'a';' 替换会违反语法。

我想知道有没有办法在不修改的情况下插入字符串?我想到用\' 替换',这是个好主意吗?

我也尝试用?替换查询字符串中的{0}

query = "INSERT INTO post (title, countVote, lastReplyTime, lastReplyerId, posterId, content, plainContent, relateUnit) VALUES (?, ?, ?, ?, ?, ?, ?, ?);"

cursor.execute(query, tuple(param))
# cursor.execute(query, [param,])

两者都给我错误

_mysql_exceptions.ProgrammingError: not all arguments converted during string formatting

【问题讨论】:

  • 您使用的是哪种 MySQL 连接器?如果您使用mysql-connector-python,您应该使用formatpyformat 样式作为变量的符号。你能缩小导致问题的变量范围吗?它是什么类型的?
  • @yvesonline 感谢您的评论,我正在使用MySQLdb。我不太明白你在Can you narrow down which variable is causing the problem? 中的意思。如果您问我的问题,它是类型为字符串的内容变量。如果你问我在底部粘贴的错误,我想不通。
  • 看看我的回答,看看这是否能让你更进一步。

标签: python mysql sql mysql-python


【解决方案1】:

根据您使用的信息MySQLdb

  • 尝试将format 用于parameter marker formatting,即%s%d 等等,见下文,我假设所有内容都是一个字符串,这很可能是错误的。
  • 确保转义%,请参阅文档:Note that any literal percent signs in the query string passed to execute() must be escaped, i.e. %%. 在适用的情况下执行此操作,我为post.contentpost.plain_content 做了示例。
query = "INSERT INTO post (title, countVote, lastReplyTime, lastReplyerId, posterId, content, plainContent, relateUnit) VALUES (%s, %s, %s, %s, %s, %s, %s, %s);"
cursor.execute(query,post.title, post.count_vote, post.last_reply_time, post.last_replyer_id, post.poster_id, post.content.replace("%", "%%"), post.plain_content.replace("%", "%%"), post.relate_unit)

【讨论】:

  • 感谢您的回答,post.count_vote 等可以作为列表传递吗?老实说,post 对象有 30 多个字段。我在我的问题中省略了不相关的问题。我还将 cursor.execute 封装到一个函数中,以便我可以在其他对象中使用它,例如评论、回复。
  • 我尝试用%s 替换?,但程序在' 也崩溃了。我决定将' 替换为\' 以节省我的时间。
猜你喜欢
  • 2017-06-13
  • 1970-01-01
  • 1970-01-01
  • 2020-04-28
  • 2019-05-18
  • 1970-01-01
相关资源
最近更新 更多