使用python和postgres,execute函数中的变量? [英] Using python and postgres, variables within execute function?

查看:474
本文介绍了使用python和postgres,execute函数中的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对访问PostgreSQL服务器的python函数中变量的用法有疑问.例如,以下内容:

I had a question regarding the usage of variables inside a python function which accesses the PostgreSQL server. For example, the following:

def delete():
    cur.execute(
    """DELETE FROM potluck 
    WHERE name = var_1;"""

但是,如果我希望更新函数为var_1接受变量,我该怎么做?

However, If I wanted the update function to take in variables for var_1, how would I do so?

例如,我希望我的函数采用以下形式:

For example, I want my function to be in the form:

def delete(var_1):
    cur.execute(
    """DELETE FROM potluck 
    WHERE name = %s;""", (var_1))

但是,仅仅键入那是行不通的.

However, just typing that didn't work.

此外,在以下情况下如何处理

In addition, how about in the case when:

def delete(name, var_1):
    cur.execute(
    """DELETE FROM potluck 
    WHERE %s = %s;""", (name, var_1))

我不希望将名称"插入字符串时用引号引起来吗?

where I don't want "name" to have quotation marks when it is inserted into the string?

任何帮助将不胜感激!

推荐答案

已解决:

我知道我做错了.我唯一需要做的更改是在var_1之后添加一个逗号,因为: 对于位置变量绑定,即使第二个参数包含一个变量,第二个参数也必须始终是一个序列.请记住,Python需要用逗号来创建单个元素元组."

I see what I was doing wrong. The only change I needed to make was add a comma after var_1, since: "For positional variables binding, the second argument must always be a sequence, even if it contains a single variable. And remember that Python requires a comma to create a single element tuple".

例如:

def delete(var_1):
    cur.execute(
    """DELETE FROM potluck 
    WHERE name = %s;""", (var_1,))

这有效.我从以下位置获得了信息:

This works. I got the info from:

http://initd.org/psycopg/docs/usage.html# sql-injection

在第二种情况下,请参考以下使用AsIs的其他答案.那个有效.例如:

In the second case, then please reference the other answer below, which uses AsIs. That works. For example:

def delete(name, var_1):
    cur.execute(
    """DELETE FROM potluck 
    WHERE %s = %s;""", (AsIs(name), var_1))

就可以了.谢谢!

这篇关于使用python和postgres,execute函数中的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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