首页 > 解决方案 > 如何使用 .env 文件修复 sqlalchemy create_engine 的字符串格式?

问题描述

我正在尝试在虚拟环境中使用 python 将数据帧写入 sql server。我可以使用我的 pyodbc 连接从服务器读取数据,但无法使用该连接对其进行写入,因此我使用的是 sqlalchemy 引擎,并且凭据存储在 .env 文件中。

打印原始字符串返回:

'mssql+pyodbc://User:Password@Server/Database?trusted_connection=no&driver=ODBC+Driver+17+for+SQL+Server'

但是在打印引擎时它会返回:

'mssql+pyodbc://User:***sword@Server/Database?trusted_connection=no&driver=ODBC+Driver+17+for+SQL+Server'

如果我尝试使用引擎进行连接,登录超时将过期,我假设这是因为引擎没有传递正确的凭据。

我的字符串格式有什么问题吗?

import os
from sqlalchemy import create_engine
from dotenv import load_dotenv

load_dotenv()

credentials = [os.getenv('UID'), os.getenv('PWD'), os.getenv('Server'), os.getenv('Database')]

engine = create_engine('mssql+pyodbc://{0}:{1}@{2}/{3}?trusted_connection=no&driver=ODBC+Driver+17+for+SQL+Server'.format(*credentials),fast_executemany=True)

print('mssql+pyodbc://{0}:{1}@{2}/{3}?trusted_connection=no&driver=ODBC+Driver+17+for+SQL+Server'.format(*credentials))
print(engine)

engine.connect()

标签: sql-serversqlalchemyenvironment-variablespython-3.9string.format

解决方案


推荐阅读