分享一个通过python执行sql语句的模板

def execute(self ,sql):
    """直接执行SQL语句,不处理返回值"""
    # 拿到游标
    cursor = self.conn.cursor()
    # 执行SQL
    try:
        cursor.execute(sql)
        logger.debug(f"执行了一条SQL:{
      
      sql}")
    except Exception as e:
        logger.error(e)
        # logger.error(traceback.format_exc())
	
	# =======================二选一即可 ====================

    # 方式1:
    if not self.conn.get_autocommit():
        self.conn.commit()

    # 方式2:
    if self.conn.get_autocommit():
        # 不做任何事情,一般用做占位语句
        pass
    else:
        self.conn.commit()
	# =======================二选一即可 ====================
    # 关闭游标
    cursor.close()

猜你喜欢

转载自blog.csdn.net/weixin_44976611/article/details/129220733
今日推荐