(python) 数据库一次 Connection 连接,不同 cursor

数据库一次 Connection 连接,不同 cursor 的最简洁代码:

import pymysql


class Database(object):
    connection = None

    def __init__(self):
        if not Database.connection:
            Database.connection = pymysql.connect(host="127.0.0.1",
                                                  port=xxx,
                                                  user="xxx",
                                                  password="xxx",
                                                  database="dbtest")

    def query(self, sql):
        cursor = Database.connection.cursor()
        cursor.execute(sql)

if __name__ == '__main__': db = Database() db.query()
posted on 2023-05-08 16:29  bruce_he  阅读(85)  评论(0编辑  收藏  举报