You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用SQLAlchemy create_engine连接SQL Server时隐藏密码的问题

Python导入SQL Server隐藏凭据失败的解决办法

我需要将Python生成的表格导入公司的SQL Server数据库,希望隐藏SQL Server凭据。当前代码可正常运行,但因代码将部署在公司虚拟机自动执行,需隐藏密码。尝试使用keyring工具获取凭据,替换连接字符串中的密码为变量后,出现“Error validating credentials due to invalid username or password”错误,推测是连接字符串中的变量未被解析导致。

原可正常运行的代码

engine = sqlalchemy.create_engine(
    "mssql+pyodbc://trevor@email.com:mypassword!@dsn"
    "?authentication=ActiveDirectoryPassword"
)

df.to_sql('df', con = engine, schema= 'dbo', if_exists='replace', index=False)

尝试的keyring代码

import keyring

creds = keyring.get_credential(service_name= "sqlupload", username = None)
username_var = creds.username
password_var = creds.password

替换密码后出错的连接代码

engine = sqlalchemy.create_engine(
    "mssql+pyodbc://trevor@email.com:password_var@dsn"
    "?authentication=ActiveDirectoryPassword"
)

df.to_sql('df', con = engine, schema= 'dbo', if_exists='replace', index=False)

问题原因及解决方法

问题出在你直接把变量名password_var写进了字符串常量里,Python不会自动解析字符串中的变量名,导致连接字符串里的密码变成了字面量password_var,而非变量存储的真实密码。

推荐解决方案:使用f-string格式化连接字符串

这是Python 3.6及以上版本最简洁的方式,直接在字符串前加f,并用{}包裹变量名,Python会自动替换变量值:

engine = sqlalchemy.create_engine(
    f"mssql+pyodbc://{username_var}:{password_var}@dsn"
    "?authentication=ActiveDirectoryPassword"
)

备选方案:使用str.format()格式化

如果你的Python版本低于3.6,可以用这种方法:

engine = sqlalchemy.create_engine(
    "mssql+pyodbc://{}:{}@dsn?authentication=ActiveDirectoryPassword".format(
        username_var, password_var
    )
)

额外优化:动态传入用户名

既然已经通过keyring获取了用户名,建议把硬编码的用户名也换成变量,避免后续用户名变动时修改代码:

# 直接用keyring获取的用户名变量,无需硬编码
engine = sqlalchemy.create_engine(
    f"mssql+pyodbc://{username_var}:{password_var}@dsn"
    "?authentication=ActiveDirectoryPassword"
)

内容的提问来源于stack exchange,提问作者Trevor M

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 03:58:38