我想从数据库“详细信息”中检索值,因为我只想与 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。