2

我有一个 python 脚本,它总是在后台运行

nohup python script.py &

所以脚本的作用是:它检查 mqtt 是否有任何消息,如果为真,则将其插入数据库

on_message(client, userdata, msg):
    SQL.execute("INSERT INTO logs(deviceID) VALUES (msg)")

我使用这种方式连接到数据库,但几个小时后连接关闭并且脚本正在运行但它无法插入到数据库

mydb = mysql.connector.connect(host="localhost",  user="xxxx",  passwd="xxxx",  database="xxx")
SQL = mydb.cursor()

问题:

  1. 我需要每次在SQL.execute()之前打开新连接还是更好地保持打开状态?
  2. 你能添加你认为更好用的代码吗
4

2 回答 2

0

最好在需要时打开连接,而不是简单地保持打开状态,因为这会浪费大量资源。

您可以将装饰器添加到像这样的任何数据库处理程序函数中,以在引发异常“MySQL 服务器已消失”时重新连接 MySQL 数据库。从这里获取的代码

class DB:
    """Database interface"""

    def retry(func):
        def call(self, *args, **kwargs):
            lock.acquire()
            try:
                return func(self, *args, **kwargs)
            except MySQLdb.Error, e:
                if 'MySQL server has gone away' in str(e):
                    # reconnect MySQL
                    self.connect_mysql()
                else:
                    # No need to retry for other reasons
                    pass
            finally:
                lock.release()
        return call

    def __init__(self):
        pass

    def connect_mysql(self):
        # create connection here

    @retry
    def execute(self):
        # use the decorator to get conenction and do you SQL.execute() here
于 2020-03-29T16:27:05.650 回答
0

您的消息频率如何?如果它们不是太频繁,我只需try 打开连接,插入,然后在else. 连接是系统资源,你不应该浪费它们。

此外,一些数据库引擎,不知道 mysql,会定期对长空闲连接进行垃圾收集,当您尝试使用它时,您的连接会意外关闭。


on_message(client, userdata, msg):

    try:
        mydb = mysql.connector.connect(host="localhost",  user="xxxx",  passwd="xxxx",  database="xxx")
        SQL = mydb.cursor()
        #☝️ use mysqls parametrized queries
        SQL.execute("INSERT INTO logs(deviceID) VALUES (%s)", (msg,))
    except Exception as e:
        raise
    else:
        SQL.close()

于 2020-03-29T16:20:07.850 回答