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 내가 위의 DSN을 정의 할 수있는 방법을 는 ...이 인수 한 정의입니다 걸립니다.
, 그것을 제거하고 내가 한 번만 DB와 연결하고 데이터에 액세스 할 – sneawo