zoukankan      html  css  js  c++  java
  • 数据库操作封装代码示例

    import pymysql
    
    
    class DBHandler():
        """数据库操作"""
    
        def __init__(self, host='',
                     port= ,
                     username='',
                     password='',
                     db_name='f'
                     ):
            # 得到一个连接对象
            self.connection = pymysql.connect(host=host,
                                              port=port,
                                              user=username,
                                              password=password,
                                              database=db_name)
    
        def query_one(self, sql):
            """查询一条记录"""
            # 得到游标
            cursor = self.connection.cursor()
            # 提交,同步最新的数据库信息
            self.connection.commit()
            # 执行
            cursor.execute(sql)
            # 得到执行结果
            data = cursor.fetchone()
            # 关闭游标
            cursor.close()
            return data
    
        def query_all(self, sql):
            """查询所有的记录"""
            cursor = self.connection.cursor()
            # 提交
            self.connection.commit()
    
            cursor.execute(sql)
            data = cursor.fetchall()
            cursor.close()
            return data
    
        def close(self):
            self.connection.close()
    
    
    # 判断是否是主程序运行,如果不是主程序运行,就不执行下面的代码,方便debug
    if __name__ == '__main__':
        # 简单的测试代码。
        db = DBHandler()
        ret = db.query_one('select reg_name, id from member limit 5;')
        print(ret)
        db.close()
  • 相关阅读:
    Python一键安装缺失库
    Python画樱花树❀
    Python时间模块time
    Python的画五角星
    力扣225.用队列实现栈
    STL是个啥?
    如何使用递归遍历对象获得value值
    JS操作未跨域iframe里的DOM
    CSS3D效果
    前端轮播小结
  • 原文地址:https://www.cnblogs.com/wsfsd/p/15469803.html
Copyright © 2011-2022 走看看