如何使用Python的cx_Oracle模块执行Oracle SQL并生成HTML报表
你之前使用的SET MARKUP HTML、spool属于SQL*Plus客户端的专属指令,不是标准SQL,无法直接通过cx_Oracle执行。正确的实现方式是在Python侧获取SQL查询结果后,自行拼接生成符合样式要求的HTML报表,整合后的完整代码如下:
import cx_Oracle import datetime import logging # 配置日志基础设置,避免logging报错 logging.basicConfig(level=logging.INFO) def main(env_name="ABC_DEV_KK"): try: # 修正原代码的语法错误:datetime赋值、变量拼写 now = datetime.datetime.now() dt_string = now.strftime("%Y%m%d") # 修正Oracle连接写法,按你实际的连接配置调整即可 connection = cx_Oracle.connect(user="username", password="pass", dsn=env_name) cursor = connection.cursor() # 使用参数绑定替代字符串拼接,避免SQL注入风险 sql = "Select * from hr.departments where date = :dt" cursor.execute(sql, dt=dt_string) # 获取查询列名,用于生成HTML表头 columns = [desc[0] for desc in cursor.description] res = cursor.fetchall() # 拼接HTML内容,完全匹配你之前的样式配置 html_content = f""" <!DOCTYPE html> <html> <head> <TITLE>EMPLOYEE REPORT</TITLE> <STYLE type='text/css'> BODY {{background: #FFFFC6; color:#FF00Ff}} table {{width:90%; border:5px solid; border-collapse: collapse;}} th, td {{border:1px solid; padding: 8px;}} </STYLE> </head> <body> <table> <tr>{"".join(f"<th>{col}</th>" for col in columns)}</tr> {"".join(f"<tr>{''.join(f'<td>{cell}</td>' for cell in row)}</tr>" for row in res)} </table> </body> </html> """ # 写入HTML文件 with open("report2.html", "w", encoding="utf-8") as f: f.write(html_content) logging.info("HTML报表生成成功:report2.html") # 关闭连接 cursor.close() connection.close() except Exception as e: logging.error(f"执行报错:{e}") if __name__ == '__main__': main()
代码说明:
- 修正了原脚本中的多处语法错误:
datetime调用写法、__name__双下划线拼写、Oracle连接调用方式 - 采用参数绑定方式传递查询日期,避免SQL注入风险
- 生成的HTML样式完全匹配你之前SQL*Plus指令中配置的效果
内容的提问来源于stack exchange,提问作者unknown
相关产品推荐
相关产品推荐

