如何使用Session或引擎查询原始SQL

时间:2017-01-18 03:35:20

标签: python sql session orm sqlalchemy

使用ParentChild表:

from sqlalchemy import Column, ForeignKey, String, create_engine, desc, asc
from sqlalchemy.ext.declarative import declarative_base
import uuid

Base = declarative_base()
class Parent(Base):
    __tablename__ = 'parents'
    uuid = Column(String(64), primary_key=True, unique=True)
    def __init__(self):  
        self.uuid = uuid.uuid4()   

class Child(Base):
    __tablename__ = 'children'
    uuid = Column(String(64), primary_key=True, unique=True)
    parent_uuid = Column(String(64), ForeignKey('parents.uuid'))
    def __init__(self, parent_uuid=None):  
        self.uuid = uuid.uuid4()   
        self.parent_uuid = parent_uuid

我可以继续创建一个Parent实体:

engine = create_engine('mysql://root:pass@localhost/dbname', echo=False)
session = scoped_session(sessionmaker()) 
session.remove()
session.configure(bind=engine, autoflush=False, expire_on_commit=False)

parent = Parent()
session.add(parent)
session.commit()
session.close()

生成的parent变量是常规的Python ORM对象。

如果我要查询数据库而不是创建一个数据库,查询结果将是一个ORM对象列表:

result = session.query(Parent).order_by(desc(Parent.uuid)).all()

但有时我们需要使用原始Sql命令查询数据库。 有没有办法使用session对象运行原始SQL命令,以确保生成的查询返回是ORM对象还是对象列表?

1 个答案:

答案 0 :(得分:3)

您可以使用会话的session.execute('select * from table') 方法:

public class CommentPage extends FormPage{
  private FormToolkit toolkit;

  public CommentPage (FormEditor editor, String id, String title) {
    super(editor, id, title);
  }
  @Override
  protected void createFormContent(IManagedForm managedForm) {
    // TODO Auto-generated method stub
    super.createFormContent(managedForm);
    toolkit = managedForm.getToolkit();
    form = managedForm.getForm();
    toolkit.decorateFormHeading(form.getForm());
    form.setText(currVersion.getcName()+currVersion.getvName());
    Composite superContainer = form.getBody();
    superContainer.setLayout(new GridLayout(2,false));
    superContainer.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
    createAreas(superContainer);
  }

  private void createAreas(Composite superContainer) {
    Composite left = toolkit.createComposite(superContainer, SWT.NONE);
    Composite right = toolkit.createComposite(superContainer, SWT.NONE);
    GridData leftGrid = new GridData(SWT.FILL,SWT.FILL,true,true);
    left.setLayoutData(leftGrid);
    left.setLayout(new GridLayout(1,true));
    GridData rightGrid = new GridData(SWT.FILL,SWT.FILL,true,true);
    right.setLayoutData(new GridData(SWT.FILL,SWT.FILL,true,true));
    right.setLayout(new GridLayout(1,true));
    commentArea(right);
  }

  private void commentArea(Composite superContainer) {
    Section section = toolkit.createSection(superContainer, Section.TITLE_BAR|Section.TWISTIE|Section.EXPANDED);
    section.setText("Comment"); //$NON-NLS-1$
    section.setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
    section.setLayout(new FillLayout());

    Composite container = toolkit.createComposite(section, SWT.NONE);
    container.setLayout(new GridLayout(1, true));
    section.setClient(container);

    ScrolledComposite scrollContainer = new ScrolledComposite(container, SWT.V_SCROLL|SWT.BORDER);
    scrollContainer.setLayoutData(new GridData(SWT.FILL,SWT.FILL,true,false));
    scrollContainer.setExpandVertical(true);
    scrollContainer.setAlwaysShowScrollBars(true);
    Color white = Display.getCurrent().getSystemColor(SWT.COLOR_WHITE);
    scrollContainer.setBackground(white);

    Composite scrollInner = new Composite(scrollContainer, SWT.NONE);
    scrollInner.setBackground(white);
    scrollInner.setLayout(new GridLayout(1,false));

    Label text = toolkit.createLabel(scrollInner, "test1test2test3");
    text.setLayoutData(new GridData());

    scrollContainer.setContent(scrollInner);
    //scrollContainer.setMinSize(scrollInner.computeSize(SWT.DEFAULT, SWT.DEFAULT));

  }
}

执行方法的文档可以在这里找到:

http://docs.sqlalchemy.org/en/latest/orm/session_api.html#sqlalchemy.orm.session.Session.execute

请注意,这不能防止SQL注入。