Python postgresql变量声明

Python postgresql变量声明,python,python-3.x,postgresql,Python,Python 3.x,Postgresql,我想问一下如何在sql查询中声明变量“mobile”? 我可以使用.format()打印手机,但查询cur.execute()不起作用。如何声明查询的“mobile”变量以更新数据库? 另外,我还有一个名为currentNum.txt的文本文件,其中唯一的值是639662146331(请注意,这应该是一个字符串) 提前谢谢你 import psycopg2 import os try: conn = psycopg2.connect("dbname='database

我想问一下如何在sql查询中声明变量“mobile”? 我可以使用.format()打印手机,但查询cur.execute()不起作用。如何声明查询的“mobile”变量以更新数据库? 另外,我还有一个名为currentNum.txt的文本文件,其中唯一的值是639662146331(请注意,这应该是一个字符串) 提前谢谢你

import psycopg2
import os

try:
        conn = psycopg2.connect("dbname='database' user='postgres' password='password'")
        print("Connected to database.")
except:
        print("Unable to connect to database.")

cur = conn.cursor()

try:
        list=open("currentNum.txt", "r")
        mobile=list.readline()
# It doesn't update the database 
        cur.execute("UPDATE notif_counter SET status='Notify' WHERE mobile='{0}'".format(mobile))
        conn.commit();
# This is working
        print("Table notif_counter where mobile {0} successfully updated.".format(mobile))
        list.close()
except:
        print("Failed to update the table for notif_counter")
finally:
        if(conn):
                cur.close()
                conn.close()
                print("PostgreSQL connection is closed.")

看起来您忘记删除尾随空格了,请使用.strip()

到底是什么不起作用?你有什么错误吗?您确定数据库中有该记录吗?我没有收到任何错误,但它不会在此代码中更新数据库。它不会更新数据库“%cur.execute”(“update notif_counter SET status='Notify'WHERE mobile='{0}'”。format(mobile))您将使用此代码注入sql。。。您应该真正使用绑定替换(尽管这实际上不是您所面临的问题),您应该更改为
cur.execute(“UPDATE notif\u counter SET status='Notify'WHERE mobile=%s”,(mobile),)
使用字符串格式将变量传递给SQL查询容易出错,并且易于SQL注入。正确的方法是使用驱动程序的占位符,并将变量分别传递给
execute()
list = open("input.txt",'r')
mobile = list.readline().strip()
cur.execute("UPDATE notif_counter SET status='Notify' WHERE mobile='{}'".format(mobile))