2024-02-22 14:09:40 版本 : pyton从SQLSERVER数据库中查询结果写入HTML文件并打包成exe文件
作者: 周杨 于 2024年02月22日 发布在分类 / 计算机应用 / 编程 下,并于 2024年02月22日 编辑
 历史版本

备注 修改日期 修改人
内容更新 2024-02-23 10:18:13[当前版本] 周杨
创建版本 2024-02-22 14:09:40 周杨

主要代码来自"文心一言大模型"

主要代码


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


注意事项

1.数据库驱动

连接SQL Server 2012时,使用“ODBC Driver 17 for SQL Server”和“ODBC Driver 18 for SQL Server”驱动都无法正常连接数据库,用系统默认的“SQL Server”驱动,反而正常了

2.打包exe

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运行,则正常。


历史版本-目录  [回到顶端]
    知识分享平台 -V 5.1.4 -大信谛威