如何在SQLAlchemy中为MSSQL设置架构?

时间:2017-11-02 14:23:56

标签: python sql-server sqlalchemy database-schema pymssql

我目前这样做:

#!/usr/bin/env python

# 3rd party modules
from sqlalchemy import create_engine  # requires pymssql

# local modules
from config import cfg

connection_string = 'mssql+pymssql://{user}:{password}@{host}:{port}/{db}'

engine = create_engine(connection_string
                       .format(host=cfg['db']['host'],
                               db=cfg['db']['database'],
                               user=cfg['db']['user'],
                               password=cfg['db']['password'],
                               port=cfg['db']['port'],
                               schema=cfg['db']['schema']))

with engine.begin() as conn:
    sql = ('SELECT foo FROM bar;')
    rows = conn.execute(sql)
    print(rows)

但是我得到了

  File "/usr/local/lib/python3.5/dist-packages/sqlalchemy/engine/default.py", line 470, in do_execute
    cursor.execute(statement, parameters)
  File "pymssql.pyx", line 464, in pymssql.Cursor.execute (pymssql.c:7491)
sqlalchemy.exc.ProgrammingError: (pymssql.ProgrammingError) (208, b"Invalid object name 'bar'.DB-Lib error message 20018, severity 16:\nGeneral SQL Server error: Check messages from the SQL Server\n") [SQL: 'SELECT foo FROM bar;']

我认为问题在于我必须使用架构exampleschema。我可以通过DBeaver使用相同的凭据访问模式bar中的列foo的表exampleschema

但是当我将/{schema}添加到连接字符串时,我得到了

sqlalchemy.exc.OperationalError: (pymssql.OperationalError)
    (18456,
     b"Login failed for user 'exampleuser'.DB-Lib error message 20018,
     severity 14:\nGeneral SQL Server error: Check messages from the SQL Server\nDB-Lib error message 20002,
     severity 9:\nAdaptive Server connection failed (192.168.123.456:1433)\n")

如何设置架构?

3 个答案:

答案 0 :(得分:6)

您还可以在类定义中指定架构名称(这不是您的特定情况,但我认为这是一种常见情况)。

例如,如果在“动物”模式中有一个表“ dog”:

from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()

class Notification(Base):
    __tablename__ = "dog"
    __table_args__ = {"schema": "animal"}
    id = Column(Integer, primary_key=True)
    name = Column(String)

答案 1 :(得分:2)

阅读此SO问题Possible to set default schema from connection string?似乎无法使用连接字符串选择模式。

尝试完整的合格名称:

Backendless.Persistence.of( "Contact" ).find( new AsyncCallback<List<Map<String, Object>>>(){
  @Override
  public void handleResponse( List<Map<String, Object>> foundContacts )
  {
    Iterator<Map<String, Object>> contactsIterator = foundContacts.iterator();
    while( contactsIterator.hasNext() )
    {
      Map<String, Object> contact = contactsIterator.next();
      String name = (String) contact.get( "name" ); // in case you have STRING field 'name' in Backendless database
      Integer age = (Integer) contact.get( "age" ); // in case you have INT field 'age' in Backendless database
      // etc.
    }
  }
  @Override
  public void handleFault( BackendlessFault fault )
  {
    System.out.err( "Failed find: " + fault );
  }
});

答案 2 :(得分:0)

如果从数据库加载元数据并从元数据加载表,则可以在表加载期间设置架构。

然后创建一个会话并查询表

from sqlalchemy import MetaData, Table
from sqlalchemy.orm import sessionmaker
table = Table({Table Name}, {metadata}, autoload=True, autoload_with={engine}, schema={Schema name})

Session = sessionmaker()
Session.configure(bind={engine})
session = Session()
query = session.query(table)