• 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;")
  • 相关阅读:
    asp.net页面刷新后样式就发生了改变
    ASP.NET MVC 入门系列教程
    javascript打开邮箱服务器
    jquery验证邮箱
    MySQL数据库的索引类型
    JS判断浏览器
    Silverlight 3 新特性
    moss 2007 添加关键字及最佳匹配
    vs2008 常用快捷键
    Microsoft Enterprise Library 5.0正式版本已经发布
  • 原文地址:https://www.cnblogs.com/jianjiacangcang/p/15201052.html
Copyright © 2020-2023  润新知