Python3 使用变量 vs 函数进行连接的 psycopg2 承诺问题

Python3 psycopg2 commitment issue using variable vs function for connection

有人可以向我解释为什么定义的 test().commit() 不能像 varcon.commit() 那样工作吗?其他一切似乎工作正常。 (使用 ubuntu-trusty-32 的 vagrant virtualbox)

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import psycopg2

varcon = psycopg2.connect('dbname=tournament')

def test():
     try:
         psycopg2.connect("dbname=tournament")
     except:
         print("Connection to Tournament Database Failed")
     else:
         return psycopg2.connect('dbname=tournament')


def writer():
    #db = psycopg2.connect('dbname=tournament')
    c =varcon.cursor()
    c.execute('select * from players')
    data = c.fetchall()
    c.execute("insert into players (name) values ('Joe Smith')")
    varcon.commit()
    varcon.close
    print(data)

def writer2():
    #db = psycopg2.connect('dbname=tournament')
    c =test().cursor()
    c.execute('select * from players')
    data = c.fetchall()
    c.execute("insert into players (name) values ('Joe Smith')")
    test().commit()
    test().close
    print(data)    

writer2()   #this seem not commited, but database registers the insert by observing the serial promotion
#writer()  # this works as expected

可能是因为函数块 (def) 中的 return 语句不等于 = 之类的赋值 psycopg2 连接函数 returns 一个连接对象并将其分配给 connvarcon

conn = psycopg2.connect("dbname=test user=postgres password=secret")

http://initd.org/psycopg/docs/module.html

test() 函数也 returns psycopg2 连接对象但是在 writer2 它没有分配给变量(内存位置)意味着有没有参考

这也解释了为什么建立了数据库连接(在测试函数中初始化)但是提交不起作用(损坏的引用)

(http://www.icu-project.org/docs/papers/cpp_report/the_anatomy_of_the_assignment_operator.html)

也许试试

ami=test()

ami.commit()

建立参考

每次调用 psycopg2.connect() 都会打开 新的 数据库连接。

如此有效,您的代码在一个连接中执行 SQL,提交另一个连接,然后关闭第三个连接。即使在您的 test() 函数中,您也打开了两个不同的连接。

我使用以下模式访问 PostgreSQL:

conn = psycopg2.connect(DSN)

with conn:
    with conn.cursor() as curs:
        ...
        curs.execute(SQL1)

with conn:
    with conn.cursor() as curs:
        ...
        curs.execute(SQL2)

conn.close()

with 语句确保事务在您的 SQL 周围打开并正确提交。如果您在 with 中的代码引发异常,它还会自动回滚事务。

参考:http://initd.org/psycopg/docs/usage.html#with-statement