【发布时间】:2020-07-15 11:54:37
【问题描述】:
这与imploding a list for use in a python MySQLDB IN clause和python 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,您应该使用format或pyformat样式作为变量的符号。你能缩小导致问题的变量范围吗?它是什么类型的? -
@yvesonline 感谢您的评论,我正在使用MySQLdb。我不太明白你在
Can you narrow down which variable is causing the problem?中的意思。如果您问我的问题,它是类型为字符串的内容变量。如果你问我在底部粘贴的错误,我想不通。 -
看看我的回答,看看这是否能让你更进一步。
标签: python mysql sql mysql-python