【问题标题】:Sqlalchemy is using the schema name instead of db name in USE commandSqlalchemy 在 USE 命令中使用模式名称而不是数据库名称
【发布时间】:2020-02-14 18:10:38
【问题描述】:

我正在尝试使用 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',)]

【问题讨论】:

    标签: python sql-server sqlalchemy pymssql


    【解决方案1】:

    这似乎是 SQLAlchemy 中的一个错误。我已经打开了issue on GitHub,并且下一个版本 (1.4) 中将包含一个补丁来修复它。

    【讨论】:

      【解决方案2】:

      您似乎需要使用名称并使用冒号传递。

      pymssql
      engine = create_engine('mssql+pymssql://scott:tiger@hostname:port/dbname')
      

      【讨论】:

      • 用户名和密码正确,可以正常连接数据库,错误是尝试在元数据中反映数据库
      猜你喜欢
      • 1970-01-01
      • 2012-05-07
      • 2015-09-13
      • 2018-01-10
      • 2015-05-07
      • 2017-02-26
      • 2015-01-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多