【发布时间】:2021-10-30 08:40:32
【问题描述】:
我正在编写一个将数据从 Access 数据库传输到 MySQL 数据库的脚本。我正在尝试生成类似于以下的查询:
INSERT into customers (firstname, lastname) value ('Charlie', "D'Amelio");
然而,MySQL 不喜欢上面列出的双引号。我编写了一个笨重的函数来尝试用 ' 替换 D'Amelio 中的 '。下面是创建 SQL 语句的整个函数:
def dictionary_output(dict):
output = "INSERT into lefm_customers "
fields = "(id, "
vl = "('" + id_gen() + "', "
for key in dict.keys():
# print(dict[key])
if str(dict[key]) == 'None' or str(dict[key]) == "":
pass
elif "'" in str(dict[key]):
fields = fields + str(key) + ", "
string = ""
for character in string:
if character == "'":
string += r"\'"
else:
string += character
vl = "'" + string + "', "
else:
fields = fields + str(key) + ", "
vl = vl + "'" + str(dict[key]) + "', "
fields = fields[:-2] + ")"
vl = vl[:-2] + ");"
return "INSERT into lefm_customers " + fields + " values " + vl
目前它只是完全忽略了该值。关于用什么替换 ' 或如何改进我的功能的任何提示?谢谢!
【问题讨论】:
-
使用带参数的prepared statement,就不用担心转义了。
-
您必须在值中使用双引号 char。
INSERT into customers (firstname, lastname) value ('Charlie', 'D''Amelio'); -
没有@Akina 最好使用准备好的语句
-
@nbk 关于用什么替换 ' 的任何提示 - 双引号字符。 或如何改进我的功能? - 使用准备好的语句。
-
使用this Q&A中描述的技术
标签: python mysql sql mysql-python mysql-connector