简体   繁体   English

Python:在字符串周围插入双引号或单引号

[英]Python: inserting double or single quotes around a string

Im using python to access a MySQL database and im getting a unknown column in field due to quotes not being around the variable. 我使用python来访问MySQL数据库并且因为引号不在变量周围而在字段中获取未知列。

code below: 代码如下:

cur = x.cnx.cursor()
cur.execute('insert into tempPDBcode (PDBcode) values (%s);' % (s)) 
rows = cur.fetchall()

How do i manually insert double or single quotes around the value of s? 如何在s的值周围手动插入双引号或单引号? I've trying using str() and manually concatenating quotes around s but it still doesn't work. 我尝试使用str()并手动连接s周围s引号,但它仍然无法正常工作。 The sql statement works fine iv double and triple check my sql query. sql语句工作正常iv双和三检查我的SQL查询。

You shouldn't use Python's string functions to build the SQL statement. 您不应该使用Python的字符串函数来构建SQL语句。 You run the risk of leaving an SQL injection vulnerability. 您冒着留下SQL注入漏洞的风险。 You should do this instead: 你应该这样做:

cur.execute('insert into tempPDBcode (PDBcode) values (%s);', s) 

Note the comma. 请注意逗号。

Python will do this for you automatically, if you use the database API: 如果您使用数据库API,Python将自动为您执行此操作:

cur = x.cnx.cursor()
cur.execute('insert into tempPDBcode (PDBcode) values (%s)',s) 

Using the DB API means that python will figure out whether to use quotes or not, and also means that you don't have to worry about SQL-injection attacks, in case your s variable happens to contain, say, 使用DB API意味着python将确定是否使用引号,并且还意味着您不必担心SQL注入攻击,以防您的s变量恰好包含,例如,

value'); drop database; '

If this were purely a string-handling question, the answer would be tojust put them in the string: 如果这纯粹是一个字符串处理问题,答案就是将它们放在字符串中:

cur.execute('insert into tempPDBcode (PDBcode) values ("%s");' % (s)) 

That's the classic use case for why Python supports both kinds of quotes. 这是Python支持两种引号的经典用例。

However as other answers & comments have pointed out, there are SQL-specific concerns that are relevant in this case. 但是,正如其他答案和评论所指出的那样,在这种情况下存在与SQL相关的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM