我想从数据库“details”中检索值,因为我想只创建一个与DB的连接,如果存在连接,则不建立新连接并继续前一个连接。因为我试过以下:
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个参数,一个是定义... 我该如何定义上面的dsn。
答案 0 :(得分:0)
您正在尝试重新发明连接池。
不幸的是,您的解决方案不会按原样运行。只有当所有连接参数 - 主机,端口,数据库,用户名,密码完全相同时,才能使用相同的连接。在您的情况下,您在任何情况下都返回相同的连接,这是完全错误的 - 如果任何属性不同,您必须创建新连接。
答案 1 :(得分:0)
您没有根据需要向a.connect函数提供dsn信息。将dsn信息从类中拉出并使其成为主函数的一部分。然后将其作为a.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)