如何在SQL查询的where条件中使用外部变量?

2024-06-07 13:48:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我想通过python脚本从PostgreSQL数据库获取数据。在where条件下,我必须使用一个名为“lastrun”的局部变量的值。lastrun不算什么,但我已经将程序最后一次执行的时间存储在一个文件中。读取该文件后,我将该值存储在一个名为“lastrun”的变量中,我想在查询中使用它

lastrun="06/11/2020 08:20:50.949881"
def doQuery( conn ):
    cur = conn.cursor()
    cur.execute("SELECT accountno,req, type, site,ref FROM accounts WHERE  created > lastrun")
    records=cur.fetchall()

print("Using PyGreSQL…")
import pgdb
myConnection = pgdb.connect( host=hostname, user=username, password=password, database=database )
doQuery( myConnection )
myConnection.close()

我试过了,但什么都不管用。请帮帮我。 提前谢谢


Tags: 文件脚本数据库postgresqlpasswordconnwhere条件
1条回答
网友
1楼 · 发布于 2024-06-07 13:48:24

您可以使用python字符串格式来实现这一点

lastrun="06/11/2020 08:20:50.949881"
def doQuery( conn ):
    cur = conn.cursor()
    cur.execute("SELECT accountno,req, type, site,ref FROM accounts WHERE  created > '%s'"%lastrun)
    records=cur.fetchall()

print("Using PyGreSQL…")
import pgdb
myConnection = pgdb.connect( host=hostname, user=username, password=password, database=database )
doQuery( myConnection )
myConnection.close()

欲了解更多信息,请访问here

相关问题 更多 >

    热门问题