python mysql连接自动连接错误

nom7f22z  于 2021-06-25  发布在  Mysql
关注(0)|答案(1)|浏览(332)

我的python-mysql连接有问题,需要帮助。我的设置是两个pi的运行服务器上的每一个。一个pi(solartpi)让mysql数据库收集数据。另一个pi(officepi)连接到solarpi数据库,通过网络连接检索和更新数据。
我的主脚本工作正常,直到我不得不重新启动solarpi的维护或电源问题和连接到officepi丢失。officepi上的python脚本随后进入一个错误循环“2006,mysql server已经消失”,下面是这个脚本的一个示例。

import MySQLdb

connSolar = MySQLdb.connect("192.xxx.x.x", "external", "xxxxx", "xxxxx") 

# eternal connection to solar pi database

cursSolar = connSolar.cursor()

while 1:

   try:
       cursSolar.execute("SELECT * FROM dashboard")
       connSolar.commit()
       for reading in cursSolar.fetchall():
           heatingDemand = reading[2] #get heating demand from dB
           print heatingDemand
   except (MySQLdb.Error, MySQLdb.Warning) as e:
       print (e)    

connSolar.close()

所以我试着用stackoverflow的脚本和如下所示的一个网站来重写它,但是当solarpi重新启动时,它会终止程序,并出现以下错误\u mysql\u exceptions.operationalerror:(2003,'can't connect to mysql server on'192..x'(111“connection densed”)')

import MySQLdb

class DB:
con = None

def connect(self):
    self.conn = MySQLdb.connect("192.xxx.x.x", "xxxxx", "xxxxxx", "house") #eternal connection to solar pi database

def query(self, sql):
    try:
        cursor = self.conn.cursor()
        cursor.execute(sql)
    except (AttributeError, MySQLdb.OperationalError):
        self.connect()
        cursor = self.conn.cursor()
        cursor.execute(sql)
    return cursor   

while 1:
    db = DB()
    sql = "SELECT * FROM dashboard"
    cur = db.query(sql)
    for reading in cur.fetchall():
        heatingDemand = reading[2] #get heating demand from dB
        print heatingDemand

officepi是否有办法在关闭后继续尝试连接到solarpi mysql数据库。

5t7ly7z5

5t7ly7z51#

更改代码以检查每个循环是否通过的有效连接:

import MySQLdb

class DB:

    def connect(self):
        try:
            self.conn = MySQLdb.connect("192.xxx.x.x", "xxxxx", "xxxxxx", "house")

        except (MySQLdb.Error, MySQLdb.Warning) as e:
            print (e)
            self.conn = None

    return self.conn

    def query(self, sql):
        try:
            cursor = self.conn.cursor()
            cursor.execute(sql)
        except (AttributeError, MySQLdb.OperationalError):
            self.connect()
            cursor = self.conn.cursor()
            cursor.execute(sql)
        return cursor   

while 1:
    db = DB()

    conn = db.connect()

    if conn:
        sql = "SELECT * FROM dashboard"
        cur = db.query(sql)
        for reading in cur.fetchall():
            heatingDemand = reading[2] #get heating demand from dB
            print heatingDemand

相关问题