1

データベースの「詳細」から値を取得したいので、DBとの接続を1つだけ作成したいのですが、接続が存在する場合は、新しい接続を作成せず、前の接続を続行します。そのために私は次のことを試みました:

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つの引数を取ります1つは定義されています...上記のdsnをどのように定義できますか?

4

2 に答える 2

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)
于 2012-12-17T09:19:30.560 に答える
0

接続プールを再発明しようとしています。

残念ながら、あなたのソリューションはそのままでは機能しません。すべての接続パラメーター (ホスト、ポート、データベース、ユーザー名、パスワード) がまったく同じ場合にのみ、同じ接続を使用できます。あなたの場合、どのような場合でも同じ接続を返しますが、これは単に間違っています。プロパティが異なる場合は、新しい接続を作成する必要があります。

代わりに、 pysqlpoolDBUtilsなどの既存の接続プール ライブラリの 1 つを使用してください(他にもあるはずです)。

于 2012-12-17T07:24:54.070 に答える