python - 确认 postgres 'update' 查询在 python 中有效

标签 python postgresql

我已经用 python 编写了我的第一个“更新”查询,虽然它看起来是正确的,但我不确定如何接收返回的输出以确认它有效..

这应该加载一个 CSV 文件并将第一列中的值替换为第二列中的值:

def main():
    try:
        conn=psycopg2.connect("dbname='subs' user='subs' host='localhost' password=''")
    except:
        print "I am unable to connect to the database."
        sys.exit()

    with open("dne.txt", "r+") as f:
        for line in f:
            old = line.split(',')[0].strip()
            new = line.split(',')[1].strip()
            cur = conn.cursor()
            cur.execute("UPDATE master_list SET subs = '{0}' WHERE subs = '{1}';".format(new, old))
            conn.commit()
            results = cur.fetchall()
            for each in results:
                print str(each)


if __name__=="__main__":
    main()

我认为结果(每次更改更新 1?)会以元组的形式返回,但我得到了一个错误:

psycopg2.ProgrammingError: no results to fetch

我不确定这是否意味着我的查询不起作用并且没有更新,或者我是否无法像我尝试的那样使用 fetchall()。

欢迎任何反馈或建议!

最佳答案

UPDATE 语句不会返回任何值,因为您要求数据库更新其数据而不是检索任何数据。

到目前为止,获取更新行数的最佳方法是使用 cur.rowcount。这也适用于其他驱动程序,例如用于 Postgresql 的 Psycopg2,语法相同。

cur.execute("UPDATE master SET sub = ('xyz') WHERE sub = 'abc'")
print(cur.rowcount)

检查更新的一种更迂回的方法是在更新表后对表运行 SELECT;你应该得到返回的数据。在我下面的示例中,第一个 SELECT 将返回将发生更新的行。更新后的第二个 SELECT 应该不会返回任何行,因为您已经更新了所有字段。第三个 SELECT 应返回您已更新的行,以及任何已存在且具有“xyz”值的行。

import sqlite3

def main():
    try:
        conn=sqlite3.connect(":memory:")
        cur = conn.cursor()
        cur.execute("create table master(id text, sub text)")
        cur.execute("insert into master(id, sub) values ('1', 'abc')")
        cur.execute("insert into master(id, sub) values ('2', 'def')")
        cur.execute("insert into master(id, sub) values ('3', 'ghi')")
        conn.commit()
    except:
        print("I am unable to connect to the database.")
        sys.exit()

    cur.execute("select id, sub from master where sub='abc'")
    print(cur.fetchall())
    cur.execute("UPDATE master SET sub = ('xyz') WHERE sub = 'abc'")
    conn.commit()
    cur.execute("select id, sub from master where sub='abc'")
    print(cur.fetchall())
    cur.execute("select id, sub from master where sub='xyz'")
    print(cur.fetchall())

if __name__=="__main__":
    main()

关于python - 确认 postgres 'update' 查询在 python 中有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21277636/

相关文章:

python - 计算两个文本文件的混淆矩阵

php - 将 mysql 语句切换到 postgresql

postgresql - 检查表中的 OID 大小

python - 使用 Python 覆盖率对测试结果进行分组

postgresql - 在 Postgres 的间隔中使用可变周期

sql - 在第一次引导事件发生之前查找平均观看次数

SQL嵌套请求

python - 过滤二维 numpy 数组

python - 下面的代码有更快的实现吗?

python - 使用 Scrapy 邮件模块发送电子邮件时连接被拒绝