gpt4 book ai didi

python - 使用 Python 将列表插入我的数据库

转载 作者:IT王子 更新时间:2023-10-29 00:38:56 24 4
gpt4 key购买 nike

我想在我的数据库中插入一个列表,但我不能。

这是我需要的示例:

variable_1 = "HELLO"
variable_2 = "ADIOS"
list = [variable_1,variable_2]

INSERT INTO table VALUES ('%s') % list

这样的事情能做吗?我可以插入一个列表作为值吗?当我尝试时,出现错误说这是因为 MySQL 语法错误

最佳答案

您最初问题的答案是:不,您不能插入这样的列表。

但是,通过一些调整,您可以通过使用 %r 并传入一个元组来使该代码工作:

variable_1 = "HELLO"
variable_2 = "ADIOS"
varlist = [variable_1, variable_2]
print "INSERT INTO table VALUES %r;" % (tuple(varlist),)

不幸的是,这种类型的变量插入会使您的代码容易受到 SQL injection attacks 的攻击。 .

相反,我们建议使用 Python's DB API并为要插入的数据构建带有多个问号的自定义查询字符串:

variable_1 = "HELLO"
variable_2 = "ADIOS"
varlist = [variable_1,variable_2]
var_string = ', '.join('?' * len(varlist))
query_string = 'INSERT INTO table VALUES (%s);' % var_string
cursor.execute(query_string, varlist)

SQLite3 docs 开头的例子展示了如何使用问号传递参数,并解释了为什么它们是必要的(本质上,它确保正确引用你的变量)。

关于python - 使用 Python 将列表插入我的数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8316176/

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