我想从数据库“细节”中检索值,因为我想用数据库创建一个连接,如果连接存在,请不要建立新连接并继续前一个连接。为此,我曾尝试与以下:单身数据库连接
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。
你叫a.connect无DSN参数,将其删除,并使用self.dsn – sneawo