小编Pro*_*ova的帖子

PostgreSQL + Python:关闭连接

我用Python制作了一个游戏服务器,它使用psycopg2连接到PostgreSQL数据库.我见过一些例子,我已经看到,当创建与数据库的连接时,应该在完成查询时关闭连接,例如对于每个客户端:

#create connection to db
con = psycopg2.connect (database = 'testdb', user = 'janbodnar')
cur = con.cursor ()
#process query
.
.
.
#close connection
con.close ()
Run Code Online (Sandbox Code Playgroud)

好的,当我启动我的服务器时,我有这个:

在我的课堂里

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
Run Code Online (Sandbox Code Playgroud)

也就是说,我对所有客户的所有查询使用相同的连接对象,并且从不关闭连接,这看起来比打开和关闭每个客户端的连接更好,我的服务器显然运行良好.你想到这个吗?这样做得好吗?不要做?谢谢

python

6
推荐指数
2
解决办法
1万
查看次数

标签 统计

python ×1