Python 单例数据库连接
我想从数据库“details”中检索我只想与DB建立一个连接的值,如果存在连接,不要建立新连接并继续上一个连接。为此,我尝试了以下方法:Python 单例数据库连接,python,mysql,Python,Mysql,我想从数据库“details”中检索我只想与DB建立一个连接的值,如果存在连接,不要建立新连接并继续上一个连接。为此,我尝试了以下方法: import MySQLdb import re import os class Find: def __init__(self,addr): self.addr = addr dsn = { 'username': 'xyz', 'password': 'xyz', 'hostname': 'l
import MySQLdb
import re
import os
class Find:
def __init__(self,addr):
self.addr = addr
dsn = {
'username': 'xyz',
'password': 'xyz',
'hostname': 'localhost',
'database': 'details'
}
the_database_connection = False
def connect(self,dsn):
'''This function saves the database connection, so if invoke this again, it gives you the same one, rather than making a second connection.'''
global the_database_connection
if not the_database_connection:
try:
the_database_connection = MySQLdb.connect(
host=dsn['hostname'],
user=dsn['username'],
passwd=dsn['password'],
db=dsn['database'])
# so modifications take effect automatically
the_database_connection.autocommit(True)
except MySQLdb.Error, e:
print ("Couldn't connect to database. MySQL error %d: %s" %(e.args[0], e.args[1]))
return the_database_connection
x=conn.cursor()
sql = "select * from persons where address = %s" % addr
x.execute(sql)
rows = x.fetchall()
for row in rows:
print row
if __name__ == "__main__":
a = Find(addr = "new street")
a.connect()
但是这个显示错误:a.connect接受2个参数一个是define。。。
如何定义上述dsn。您正在尝试重新创建连接池 不幸的是,您的解决方案无法按原样工作。只有当所有连接参数(主机、端口、数据库、用户名和密码)完全相同时,使用相同的连接才可行。在您的情况下,您在任何情况下都返回相同的连接,这完全是错误的-如果任何属性不同,您必须创建新的连接
相反,只需使用一个现有的连接池库,如或(我相信还有其他库)。您没有按要求向a.connect函数提供dsn信息。从类中提取dsn信息并使其成为主函数的一部分。然后将其作为.connect的参数反馈。像这样:
import MySQLdb
import re
import os
class Find:
def __init__(self,addr):
self.addr = addr
def connect(self,dsn):
'''This function saves the database connection, so if invoke this again, it gives you the same one, rather than making a second connection.'''
global the_database_connection
if not the_database_connection:
try:
the_database_connection = MySQLdb.connect(
host=dsn['hostname'],
user=dsn['username'],
passwd=dsn['password'],
db=dsn['database'])
# so modifications take effect automatically
the_database_connection.autocommit(True)
except MySQLdb.Error, e:
print ("Couldn't connect to database. MySQL error %d: %s" %(e.args[0], e.args[1]))
return the_database_connection
x=conn.cursor()
sql = "select * from persons where address = %s" % addr
x.execute(sql)
rows = x.fetchall()
for row in rows:
print row
if __name__ == "__main__":
a = Find(addr = "new street")
dsn = {
'username': 'xyz',
'password': 'xyz',
'hostname': 'localhost',
'database': 'details'
}
the_database_connection = False
a.connect(dsn)
我只想与数据库连接一次并访问数据。我不想再次触动数据库,因此需要什么样的解决方案呢?如果连接参数不同,您无法避免这种情况。如果您使用连接池,它将自动为您执行此操作,而无需您执行任何操作。参数始终相同。实际上,我被卡住了,为什么它会显示此错误。是否有任何解决方案。因此,您愿意编写一个不可重用的函数,并保证为您或以后将使用和维护该函数的人带来问题?您在不使用dsn参数的情况下调用a.connect,将其删除并使用self。dsnIt显示错误:def connect(self,self.dsn):SyntaxError:无效的语法删除了我的第二个代码段。使用第一个。如果数据库连接参数永远不会改变,那么只需在主函数开始时初始化它们。。。但我还有另一个问题:我将print语句1放在全局数据库连接之后,并将另一个print语句2放在try的末尾。当我第一次执行查询时,两条语句都打印,但另一次只有一条打印语句应该打印,为什么两条都打印?我的目标是建立一次连接,并在以后的查询中重复使用相同的连接。这样数据库连接数的限制就不会超过。听起来好像您的全局变量\u数据库\u连接工作不正常。将其作为参数传递到connect函数中,并在最后返回,而不是使其成为全局的。无论如何,它不需要全球化。另外,如果我的答案解决了您的问题,请选择它作为已回答您的问题。谢谢