在SqlAlchemy中创建动态选择查询

时间:2017-10-06 04:27:02

标签: python sqlalchemy

我已经研究了这个话题,并决定在这里问,因为我似乎无法找到任何东西。我将在下面解释:

上下文:Flask应用程序使用客户端填写的表单并发布到服务器。表单输入用于创建查询和返回数据。

我目前正在使用SQLalchemy从头开始构建查询。此时,我已成功连接到现有的Redshift数据库并可以正确查询,但我无法弄清楚如何根据用户的表单输入动态构建简单的double commission=0; String enumber; double retail_price=0; Scanner scan = new Scanner(System.in); System.out.println("Enter employee number: "); enumber= scan.nextLine(); System.out.println("Enter retail price: "); retail_price= scan.nextDouble(); System.out.println("Enter code:"); code=scan.next().charAt(0); if (code == 'A'){ commission = (retail_price/100)*6;} else if (code == 'a') {commission = (retail_price/100)*6;} else if (code == 'B') {commission = (retail_price/100)*8;} else if (code == 'b') {commission = (retail_price/100)*8;} else if (code == 'C') {commission = (retail_price/100)*10;} else if (code == 'c') {commission = (retail_price/100)*10;} else{System.out.println("Invalid code");} System.out.println("Employee number: "+enumber); System.out.println("Retail price: "+retail_price); System.out.println("Commission: "+commission); }} 语句。

主要问题是Select x, y, z不能列入python列列表。您似乎必须指定Query()这样的每个列,这些列对动态查询不起作用,因为在用户提交表单之前我不知道我想要的列。

到目前为止我的2个想法:

  1. 遍历所有列名并使用table.c.column1
  2. 使用Query.add_columns(table.c['colname'])代替select([col1, col2, ...])
  3. 使用Query()仅加载要查询的表中的特定列。不幸的是,似乎只能使用模型对象而不是反映表,除非我弄错了
  4. 这些似乎都向后退,因为它们并没有真正有效地实现我的目标。

1 个答案:

答案 0 :(得分:4)

SQLAlchemy非常灵活,因此1和2都可以完成工作。如果您不需要ORM功能,那么#2可能更自然。如果用户要传递列名列表,例如

FullTextEntityManager fullTextEntityManager =
        Search.getFullTextEntityManager(entityManager);

QueryBuilder qb = fullTextEntityManager.getSearchFactory()
        .buildQueryBuilder()
        .forEntity( MyEntity.class )
        .get();

Query luceneQuery = qb.keyword()
        .onField("xmlField_myElement_myChildElement")
        .ignoreFieldBridge()
        .matching(searchString)
        .createQuery();

List<MyEntity> results = (List<MyEntity>) fullTextEntityManager
        .createFullTextQuery( luceneQuery, MyEntity.class )
        .list();

然后,您可以使用一堆column()构造轻松地创建columns = request.args.getlist('columns')

select()

或者如果你手边有桌子,就像你提示问题一样:

stmt = select([column(c) for c in columns]).\
    select_from(some_table)

然后剩下的就是执行你的陈述:

stmt = select([table.c[c] for c in columns])
相关问题