使用Python将清单插入我的资料库

编程入门 行业动态 更新时间:2024-10-18 05:58:07
本文介绍了使用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将清单插入我的资料库

本文发布于:2023-10-24 14:13:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1524157.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:资料库   清单   Python

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!