SQLAlchemy 是一个数据库库,它(以及ORM functionality)在您提到的所有不同数据库(以及更多)中的dialects 中支持SQL generation。
在正常使用中,可以创建SQL表达式/指令(使用schema.Table object),创建database engine,然后将指令绑定到引擎,生成SQL。
但是,引擎并不是绝对必要的;每个方言都有一个compiler,可以在没有连接的情况下生成SQL;唯一需要注意的是,您需要阻止它像默认情况下那样生成绑定参数:
from sqlalchemy.sql import expression, compiler
from sqlalchemy import schema, types
import csv
# example for mssql
from sqlalchemy.dialects.mssql import base
dialect = base.dialect()
compiler_cls = dialect.statement_compiler
class NonBindingSQLCompiler(compiler_cls):
def _create_crud_bind_param(self, col, value, required=False):
# Don't do what we're called; return a literal value rather than binding
return self.render_literal_value(value, col.type)
recipe_table = schema.Table("recipe", schema.MetaData(), schema.Column("name", types.String(50), primary_key=True), schema.Column("culture", types.String(50)))
for row in [{"name": "fudge", "culture": "america"}]: # csv.DictReader(open("x.csv", "r")):
insert = expression.insert(recipe_table, row, inline=True)
c = NonBindingSQLCompiler(dialect, insert)
c.compile()
sql = str(c)
print sql
上面的例子确实有效;它假设您知道目标数据库表模式;它应该很容易适应从 CSV 导入并为多种目标数据库方言生成。