我用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)
也就是说,我对所有客户的所有查询使用相同的连接对象,并且从不关闭连接,这看起来比打开和关闭每个客户端的连接更好,我的服务器显然运行良好.你想到这个吗?这样做得好吗?不要做?谢谢
@米查?Niklas 感谢您的回答,感谢您更正 self.con 和 self.cur,我忘了输入“self”。
我澄清一下,我对服务器和数据库知之甚少。
我打算这样做:
我的服务器为每个用户处理“线程”单独的进程,然后,在每个单独的进程中,考虑为客户查询打开一个连接,然后关闭此连接,如下所示:
在我的班级中:如果来自 client1 的新请求...此客户端的“线程”,则查询运行...
def query (self):
#create connection to db for client1
con = psycopg2.connect (database = 'testdb', user = 'janbodnar')
cur = con.cursor ()
#process query for client1, for example ...
cur.execute ("DROP TABLE IF EXISTS Cars")
#close connection for this client
con.close ()
Run Code Online (Sandbox Code Playgroud)
他们对此有何看法?在我看来更好。我感谢建议和支持。
| 归档时间: |
|
| 查看次数: |
14353 次 |
| 最近记录: |