2012-12-17 3 views
1

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을 정의 할 수있는 방법을 는 ...이 인수 한 정의입니다 걸립니다.

+0

, 그것을 제거하고 내가 한 번만 DB와 연결하고 데이터에 액세스 할 – sneawo

답변

0

연결 풀을 다시 작성하려고합니다.

불행히도 귀하의 솔루션은 그대로 작동하지 않습니다. 호스트, 포트, 데이터베이스, 사용자 이름, 암호 등의 모든 연결 매개 변수가 정확히 동일 할 때만 동일한 연결을 사용할 수 있습니다. 귀하의 경우, 어떤 경우에도 동일한 연결을 반환하고 이것은 단순히 잘못된 것입니다 - 속성이 다른 경우 새 연결을 만들어야합니다.

대신 기존 연결 풀링 라이브러리 중 하나 (예 : pysqlpool 또는 DBUtils)를 사용하십시오 (다른 것들이있을 것입니다).

+0

self.dsn 사용합니다. 나는 Db를 다시 치고 싶지 않으므로 그걸 위해 필요한 해결책은 무엇입니까 –

+0

연결 매개 변수가 다르면이 문제를 피할 수 없습니다. 연결 풀러를 사용하면 아무 것도하지 않아도 자동으로 수행됩니다. – mvp

+0

매개 변수는 항상 동일합니다. –

0

필요에 따라 dsn 정보를 a.connect 함수에 제공하지 않았습니다. dsn 정보를 클래스에서 빼내 주 기능의 일부로 만드십시오. 그런 다음 a.connect의 인수로 다시 피드하십시오. 그래서 같이 : 당신은 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) 
+0

def connect (self, self.dsn) : SyntaxError : invalid syntax –

+0

두 번째 코드 단편을 제거했습니다. 첫 번째를 사용하십시오. 데이터베이스 연결 매개 변수가 변경되지 않으면 main 함수가 시작될 때 매개 변수를 초기화하십시오. – joed4no

+0

괜찮 았어 ...하지만 나는 또 다른 질문이있다 : 전 세계의 the_database_connection 후 statement1을 인쇄하고 try의 끝에 다른 print2를 넣어. 내가 두 번째 명령문을 인쇄 할 때 첫 번째 쿼리를 실행할 때 다른 인쇄 할 때 한 번만 인쇄해야하는 이유가 둘 다 인쇄되는 이유는 무엇입니까? 내 목표는 연결을 한 번 설정하고 이후의 쿼리에 동일한 연결을 다시 사용하는 것입니다. –