我想在数据库中插入一个列表,但是不能.
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将清单插入我的资料库
发布评论