Python postgresql 变量声明



我想问一下如何在sql查询上声明变量"mobile"? 我可以使用 .format(( 打印手机,但它不适用于查询 cur.execute((。我应该如何为查询声明"移动"变量以更新我的数据库? 另外供您参考,我有一个名为 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.")
list = open("input.txt",'r')
mobile = list.readline().strip()
cur.execute("UPDATE notif_counter SET status='Notify' WHERE mobile='{}'".format(mobile))

看起来你忘了删除尾随空格,使用 .strip((

最新更新