关于使用游标对象和pymysql的注释

问题描述 投票:0回答:1

在我的职能中,我这样访问数据库:

 def send_message(self, _name, _email, _message):
        if _name is None:
            custom_resp = {
                "message": "Error: No name provided",
                "status": 400
            }
            resp = jsonify(custom_resp)
            return resp
        if _email is None:
            custom_resp = {
                "message": "Error: No email provided",
                "status": 400
            }
            resp = jsonify(custom_resp)
            return resp
        if _message is None:
            custom_resp = {
                "message": "Error: No message provided",
                "status": 400
            }
            resp = jsonify(custom_resp)
            return resp
        try:
            if _name and _email and _message:
                # save edits
                sql = "INSERT INTO `contact`(`name`, `email`, `message`) VALUES(%s, %s, %s)"
                data = (_name, _email, _message)
                self.__con.checkConnectionStatus()
                cursor = self.__db.cursor(pymysql.cursors.DictCursor)
                cursor.execute(sql, data)
                self.__db.commit()
                if cursor.rowcount > 0:
                    custom_response = {
                        'status': 200,
                        'message': 'success',
                    }
                    resp = custom_response
                    return resp, 200
            else:
                custom_resp = {
                    "message": "Error: Could not proceed your request",
                    "status": 400
                }
                resp = jsonify(custom_resp)
                return resp
        except Exception as e:
            print(e)
        finally:
            if self.__con is not None:
                self.__con.closeConnection()

此代码对我来说完全可以运行。但是我得到的评论是:

在主体中创建了两个游标,最后,您要关闭其中一个,他们有不同的存储位置?您可以在光标后放置“ try”= self .__ db.cursor(pymysql.cursors.DictCursor)

self.__con.checkConnectionStatus()
                cursor = self.__db.cursor(pymysql.cursors.DictCursor)

是真的吗?我实际上没有看到任何问题,此评论可能无效。我在这里检查过:https://github.com/PyMySQL/PyMySQL/blob/master/pymysql/tests/test_DictCursor.py和这里:pymysql fetchall() results as dictionary?他们都有相同的使用方式。请给您指教!谢谢。

python flask flask-restful
1个回答
0
投票
self.__con.checkConnectionStatus()
    cursor = self.__db.cursor(pymysql.cursors.DictCursor) #cursor1

`self .__ con.checkConnectionStatus()是多余的检查。您可以从代码中删除该行。

# self.__con.checkConnectionStatus() -> remove this
cursor = self.__db.cursor(pymysql.cursors.DictCursor) #cursor2

如果以上第二行的执行失败,则会引发异常,并且将执行exceptfinally块。线路本身是对连接状态的检查,这就是使其冗余的原因。

© www.soinside.com 2019 - 2024. All rights reserved.