使用Python将清单插入我的资料库 [英] Insert list into my database using Python

查看:56
本文介绍了使用Python将清单插入我的资料库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to insert a list in my database but I can't.

以下是我需要的示例:

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

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

可以做这样的事情吗?我可以插入列表作为值吗? 当我尝试时,出现错误消息是由于MySQL语法错误

Can something like this be done? Can I insert a list as a value? When I try it, an error says that is because of an error in MySQL syntax

推荐答案

原始问题的答案是:不,您不能插入这样的列表.

The answer to your original question is: No, you can't insert a list like that.

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

However, with some tweaking, you could make that code work by using %r and passing in a tuple:

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

不幸的是,这种变量插入样式使您的代码容易受到 SQL注入攻击.

Unfortunately, that style of variable insertion leaves your code vulnerable to SQL injection attacks.

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

Instead, we recommend using Python's DB API and building a customized query string with multiple question marks for the data to be inserted:

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文档开头的示例展示了如何使用问题传递参数标记,并解释了为什么必须使用它们(本质上,它可以确保正确引用变量).

The example at the beginning of the SQLite3 docs shows how to pass arguments using the question marks and it explains why they are necessary (essentially, it assures correct quoting of your variables).

这篇关于使用Python将清单插入我的资料库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆