2

我最近开始使用 SQLALCHEMY 来查询一个 mysql 数据库。我想生成一个使用“ INTO OUTFILE <file>”语法将查询结果导出到测试文件的选择语句。例如:

SELECT *
FROM table
INTO OUTFILE '/tmp/export.txt';

有没有办法INTO OUTFILE...使用 SQLALCHEMY 生成“”子句?

如果不是,我可以继承其中一个 SQLALCHEMY 类,以便我可以自己构建该子句吗?

谢谢。

4

1 回答 1

4

我对 SQLAlchemy 站点上的示例进行了一些思考和探索,并弄清楚了。(也发布到sql-alchemy 用户食谱


from sqlalchemy import *
from sqlalchemy.sql.expression import Executable, ClauseElement
from sqlalchemy.ext import compiler

class SelectIntoOutfile(Executable, ClauseElement):
    def __init__(self, select, file):
        self.select = select
        self.file = file


@compiler.compiles(SelectIntoOutfile)
def compile(element, compiler, **kw):
    return "%s INTO OUTFILE '%s'" % (
        compiler.process(element.select), element.file
    )


e = SelectIntoOutfile(select([s.dim_date_table]).where(s.dim_date_table.c.Year==2009), '/tmp/test.txt')
print e
eng.execute(e)
于 2011-05-22T01:58:58.853 回答