主要代码来自"文心一言大模型"
import pyodbc from html import escape # 连接SQL Server数据库的参数 server = 'your_server_name' database = 'your_database_name' username = 'your_username' password = 'your_password' driver= '{ODBC Driver 17 for SQL Server}' # 或者你使用的其他驱动 # 连接数据库 conn_str = f''' DRIVER={driver}; SERVER={server}; DATABASE={database}; UID={username}; PWD={password}; ''' cnxn = pyodbc.connect(conn_str) cursor = cnxn.cursor() # 执行SQL查询 cursor.execute("SELECT * FROM your_table_name") rows = cursor.fetchall() # 生成HTML内容 html_content = f''' <!DOCTYPE html> <html> <head> <title>Database Data</title> </head> <body> <table border="1"> <tr> {','.join(['<th>{}</th>'.format(column[0]) for column in cursor.description])} </tr> ''' for row in rows: html_content += '<tr>' + ''.join(['<td>{}</td>'.format(escape(str(cell))) for cell in row]) + '</tr>' html_content += ''' </table> </body> </html> ''' # 写入HTML文件 with open('output.html', 'w', encoding='utf-8') as file: file.write(html_content) # 关闭数据库连接 cursor.close() cnxn.close() print("Data has been written to output.html")
pyhton打包成exe文件
pyinstaller --onefile db_to_html.py
连接SQL Server 2012时,使用“ODBC Driver 17 for SQL Server”和“ODBC Driver 18 for SQL Server”驱动都无法正常连接数据库,用系统默认的“SQL Server”驱动,反而正常了
python代码中调用了时间格式化代码:
formatted_time = now.strftime("%Y年%m月%d日 %H点%M分")
在python代码下运行正常,打包成exe文件运行报错,提示:UnicodeEncodeError: 'locale' codec can't encode character '\u5e74' in position 2: encoding error。“\u5e74”转成中文为“年”,将代码修改为:
formatted_time = now.strftime("%Y-%m-%d %H:%M:%S")
再打包exe运行,则正常。
查看打包后运行报错信息
尝试在命令行(例如Windows的命令提示符或PowerShell)中运行EXE文件。有时,错误信息会直接输出到命令行窗口。
import logging logging.basicConfig(filename='error.log', level=logging.ERROR) try: # 你的代码... except Exception as e: logging.error(f"发生错误: {e}", exc_info=True)
pyinstaller --onefile --console your_script.py这将确保EXE文件在运行时打开一个控制台窗口,其中可能会显示错误信息。