我用Python搭建了一个游戏服务器,使用psycopg2连接到PostgreSQL数据库。我看过示例,并且知道当连接到数据库时,应该在完成查询后关闭连接,例如对于每个客户端:
#create connection to db
con = psycopg2.connect (database = 'testdb', user = 'janbodnar')
cur = con.cursor ()
#process query
.
.
.
#close connection
con.close ()
好的,当我启动服务器时,我会看到以下内容:
在我的类中
def __init __ (self):
#create connection to db
con = psycopg2.connect (database = 'testdb', user = 'janbodnar')
cur = con.cursor ()
# to all customers ...
def query(self):
#process query, for example ...
cur.execute ("DROP TABLE IF EXISTS Cars")
#the connection never closes
也就是说,我使用同一个连接对象处理所有客户的查询,并且从不关闭该连接。与为每个客户端打开和关闭连接相比,这样做看起来更好,我的服务器显然工作得很好。您认为这样做好吗?还是不要这样做?谢谢。