我只是有一些问题如何理解类中的游标和连接。一切正常,但我不明白python如何处理连接和游标......
我有一个类来与我的数据库交互。在插入方法中,我还放置了一个“check_connection”方法,它只打印光标和连接对象。
但是我在使用插入方法后关闭了它们。当我之后调用“check_connection”对象时,我的类对象在同一位置返回对象。当我再次调用插入方法时,会创建新对象,我猜?
插入方法:
def insert_new_join(self, user, invitedby):
try:
timest = dt.now().strftime('%Y-%m-%d %H:%M:%S')
query = """ INSERT INTO user_invites (username, invitedby, dates) VALUES (%s,%s,%s) ON CONFLICT DO NOTHING"""
values = (user, invitedby, timest,)
self.connect()
self.cursor.execute(query,values)
self.con.commit()
self.check_connection()
return True
except (Exception, psy.Error) as e :
with open("errorlog.txt",'a') as f:
f.write("db insert_new_join: "+dt.now().strftime('%Y-%m-%d %H:%M:%S')+" "+str(e)+"\n")
return False
finally:
self.disconnect()
断开方法:
def disconnect(self):
if(self.cursor):
self.cursor.close()
print("PostgreSQL cursor is closed")
if(self.con):
self.con.close()
print("PostgreSQL connection is closed")
我的测试文件:
testdb = dbs.user_db(*getc.get_database_login())
testdb.insert_new_join("test","test")
testdb.check_connection()
print("\nnew insert - methode call\n")
testdb.insert_new_join("test","test")
testdb.check_connection()
这就是我的输出('xxx' 是我的数据库连接并且正常填充):
<connection object at 0x000001B442496D00; dsn: 'xxx', closed: 0>
<cursor object at 0x000001B442223900; closed: 0>
PostgreSQL cursor is closed
PostgreSQL connection is closed
<connection object at 0x000001B442496D00; dsn: 'xxx', closed: 1>
<cursor object at 0x000001B442223900; closed: -1>
new insert - methode call
<connection object at 0x000001B44253F040; dsn: 'xxx', closed: 0>
<cursor object at 0x000001B442223740; closed: 0>
PostgreSQL cursor is closed
PostgreSQL connection is closed
<connection object at 0x000001B44253F040; dsn: 'xxx', closed: 1>
<cursor object at 0x000001B442223740; closed: -1>
*self.connect() 开始连接: psycopg2.connect() 和 check_connection() 只是打印连接和游标对象,您在输出中看到的结果。
所以我的问题:
- 为什么这个调用会产生新对象?- 或者他们,我的意思是有新的内存地址
- 这是关闭连接和游标的正确方法吗?
- 此调用将在等待功能中是否有可能让连接打开并检查它们是否仍然有效?- 如果连接仍然打开但无法创建新连接,是否会像关闭 if 和异常一样执行此操作,或者是否有可能不仅检查它是否仍然打开也可以工作......或者我完全错了这意味着如果它打开它可以工作?
- 为什么游标和连接的关闭返回值不同?
- 是否创建了新的连接/光标对象,或者为什么它是新的内存地址?这是正确的做法吗(问题3)?
谢谢你们...主要是我只是想了解,因为它有效,但我尝试学习编写干净的代码:D