简体   繁体   English

如何在我的POSTGRES SQL查询中访问python中声明的变量的内容

[英]How to access content of declared Variable in python in my POSTGRES sql query

I am just getting my hand dirty with python, hence my question might look silly. 我只是用python弄污了我的手,因此我的问题可能看起来很愚蠢。 Yeah, I have the following code as per of a class. 是的,我每个班级都有以下代码。 The declared variable in python was to accepted input from the user and then cross checked the content of the variable with an POSTGRES SQL statement. python中声明的变量是要接受用户的输入,然后使用POSTGRES SQL语句对变量的内容进行交叉检查。 See the code below; 参见下面的代码;

def view_user(self):
    self.contact_modify = input('Please enter name to modify : ')
    contact_modify = self.contact_modify
    try:
        con = self.db_conn()
        print('We are connected to the db now')
    except:
        print('I can not find your database connection here')

    try:
        print(contact_modify) # to check the content of the variable
        con.execute("SELECT * FROM phone WHERE address_name = :'contact_modify'")
        print(contact_modify) # To check the contents of the variable
        while True:
            row = con.fetchone()
            if row == None:
                break
            print(row[1],row[2],row[3])
    except:
        print("Error displaying your data")

I can get the content of the declared variable named 'contact_modify' at all line of code where I print it, but my POSTGRES SQL is not getting the content hence my EXCEPT part of the code is been execute. 我可以在打印它的所有代码行中获取名为'contact_modify'的声明变量的内容,但是我的POSTGRES SQL没有得到内容,因此我代码的EXCEPT部分已执行。 I am on POSGRES-9.3 and python 3.4 on 64 Windows10 Machine. 我在64 Windows10机器上使用POSGRES-9.3和python 3.4。

Try This: 尝试这个:

  con.execute("""SELECT * FROM phone WHERE address_name ='%s';"""%(contact_modify))

If not work then do as @ Daniel Roseman said. 如果不行,那就 @ Daniel Roseman的话做。 remove try and except and see the actual error. 删除try and except然后查看实际错误。

You should pass your variable manually, like this: 您应该手动传递变量,如下所示:

conn.execute("SELECT foo FROM table where bar = '%s'" % var) 

Also, you can use .format() method. 另外,您可以使用.format()方法。

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

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