Sqlalchemy 在 USE 命令中使用模式名称而不是数据库名称

我正在尝试使用 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对象并反映引擎:


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,发现它使用 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',)]


www说
浏览 220回答 2
2回答

白板的微信

它似乎是 SQLAlchemy 中的一个错误。我在 GitHub 上打开了一个问题,下一个版本 (1.4) 中将包含一个补丁来修复它。

大话西游666

看来您需要使用名称并使用冒号传递。pymssql engine = create_engine('mssql+pymssql://scott:tiger@hostname:port/dbname')
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python