python操作mysql数据库常用操作

pip install PyMySQL

import pymysql


class MysqlHandler:

    def __init__(self, db_config):
        self.connection = pymysql.connect(**db_config)
        # self.connection.autocommit(True)
        self.cursor = self.connection.cursor()

    def query_all(self, sql):
        self.cursor.execute(sql)
        return self.cursor.fetchall()

    def query_one(self, sql):
        self.cursor.execute(sql)
        return self.cursor.fetchone()

    def query_many(self, sql, num):
        self.cursor.execute(sql)
        return self.cursor.fetchmany(num)

    def update_db(self, sql):

        try:
            self.cursor.execute(sql)
            self.connection.commit()
        except:
            self.connection.rollback()

    def __del__(self):
        """
        MysqlHandler 实例对象被释放时调用此方法,用于关闭 cursor 和 connection 连接
        """
        print("close!!!")
        self.cursor.close()
        self.connection.close()


if __name__ == "__main__":
    db = {
        "user": "root",
        "password": "123456",
        "host": "47.112.214.205",
        "port": 3306,
        "db": "BaseTestPlatform",
        "charset": "utf8mb4",
        "cursorclass": pymysql.cursors.DictCursor
    }

    my_db = MysqlHandler(db)

    r1 = my_db.query_all("select * from polls_question;")

    for i in r1:
        print(i)

    r2 = my_db.query_many("select * from polls_question;", 2)

    for i in r2:
        print(i)

    r3 = my_db.query_one("select * from polls_question where id=3;")

    print(r3)

    my_db.update_db("update polls_question set question_text=‘333‘ where id=3;")

python操作mysql数据库常用操作

上一篇:丢失更新 mysql


下一篇:Git-本地代码不能push到远程仓库系列问题-fatal: unable to access...