我正在尝试使用 SQLAlchemy 通过网络连接到 SQL Server 数据库。我在使用 pyodbc 作为驱动程序时遇到了一些麻烦,因此切换到 pymssql 并最终设法创建引擎并使用我的用户名“salas\guilherme.santo”连接到“fit_alunos”数据库中的服务器:
from sqlalchemy import create_engine, inspect
eng = create_engine('mssql+pymssql://salas\guilherme.santo:pass@server/fit_alunos?charset=utf8')
然后如果我检查引擎,一切似乎都正常:
insp = inspect(engine)
insp.default_schema_name # 'SALAS\\Guilherme.Santo'
insp.get_schema_names() # a list of schemas with the pattern SALAS\\'something'
insp.get_table_names() # all the tables in my schema, with no problem
但是如果我尝试创建一个 MetaData
对象并反射(reflect)引擎:
from sqlachemy import MetaData
meta = MetaData()
meta.reflect(bind=eng)
我收到这个OperationalError
:
OperationalError: (pymssql.OperationalError) (911, b"Database 'SALAS\\Guilherme' does not exist. Make sure that the name is entered correctly.DB-Lib error message 20018, severity 16:\nGeneral SQL Server error: Check messages from the SQL Server\n")
[SQL: use [SALAS\Guilherme]]
(Background on this error at: http://sqlalche.me/e/e3q8)
我猜测 SQLAlchemy 正在解释数据库为“SALAS\Guilherme”且架构为“Santo”,而不是数据库“fit_alunos”和架构“SALAS\Guilherme.Santo”。
有没有办法配置数据库和架构,以便它可以正确加载?
[编辑]
我使用 echo=True
运行了引擎的 Reflect 方法,发现它使用 SQL 函数获取数据库名称:
2019-10-17 16:27:16,330 INFO sqlalchemy.engine.base.Engine select db_name()
2019-10-17 16:27:16,330 INFO sqlalchemy.engine.base.Engine {}
2019-10-17 16:27:16,350 INFO sqlalchemy.engine.base.Engine use [SALAS\Guilherme]
2019-10-17 16:27:16,350 INFO sqlalchemy.engine.base.Engine {}
2019-10-17 16:27:16,389 INFO sqlalchemy.engine.base.Engine ROLLBACK
---------------------------------------------------------------------------
MSSQLDatabaseException Traceback (most recent call last)
似乎 SELECT db_name()
返回的是架构名称而不是数据库名称。
然后,我测试了获取数据库名称和模式名称的 SQL 函数的返回值,它似乎是正确的
with eng.connect() as con:
rs = con.execute("select schema_name();")
print(rs.fetchall()) # [('SALAS\\Guilherme.Santo',)]
rs = con.execute("select db_name();")
print(rs.fetchall()) # [('fit_alunos',)]
最佳答案
这似乎是 SQLAlchemy 中的一个错误。我打开了issue on GitHub下一个版本(1.4)中将包含一个补丁来修复它。
关于python - Sqlalchemy 在 USE 命令中使用架构名称而不是数据库名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58439104/