首页 > 解决方案 > Unwanted square brackets inserted in SQL statement from ORM

问题描述

I'm trying to make a simple select on my table mapped with sqlalchemy but I can't get it to match the exact table name.

As I noticed, the output of this:

class Users(base):
    __tablename__ = "users"
[...]

was

[Microsoft][SQL Server Native Client 11.0][SQL Server]Invalid object name 'users'

And I tried to fix the error by explicitly writing the database I'm refering to

class Users(base):
    __tablename__ = "[homework-3-cc-database].users"
[...]

giving the output:

[Microsoft][SQL Server Native Client 11.0][SQL Server]Incorrect syntax near ']'.

I noticed that it inserted some square brackets, unwanted. Here is their SQL statement:

[SQL: SELECT TOP 1 [[homework-3-cc-database].users].user_id AS [[homework-3-cc-database].users_user_id] 
FROM [[homework-3-cc-database].users]]

This statement, ran from DataGrip works just fine:

SELECT TOP 1 [homework-3-cc-schema].users.user_id 
FROM [homework-3-cc-schema].users

Do you have any suggestions regarding how should I fix this?

标签: sql-serverormsqlalchemy

解决方案


我必须通过以下方式指定架构名称:

__table_args__ = {"schema": "homework-3-cc-schema"}

推荐阅读