如何在SQLAlchemy中执行原始SQL?
我有一个python web应用程序,它运行在烧瓶上,并通过SQLAlchemy与数据库连接.
我需要一种方法来运行原始SQL.该查询涉及多个表连接以及内联视图.
我试过了:
connection = db.session.connection()
connection.execute( <sql here> )
Run Code Online (Sandbox Code Playgroud)
但我不断收到网关错误.
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from sqlalchemy import create_engine
connection = create_engine('mysql://user:passwd@localhost:3306/db').connect()
result = connection.execute("select * from table")
for v in result:
print v['id']
print v['name']
connection.close()
Run Code Online (Sandbox Code Playgroud)
我如何动态地获得TABLES COLUMNS NAMES?在这种情况下id,并name
我正在编写一个简单的测试,以验证“ id”列中不同值的数量是否与每个表的行数匹配。我期望能够访问对象的特定值,但是当我运行代码并尝试打印变量的值时,我可以看到我的对象是sqlalchemy.engine.result.ResultProxy对象,位于...,而不是人类可读的东西。我已经在SQLAlchemy网站上呆了一个多小时,并在Google搜索了我的问题的多个排列,但是没有找到我想要的东西。
我的代码(带终端输出)如下:
from sqlalchemy import create_engine
engine = create_engine('postgresql://kyle.pekosh@localhost:5432/testload')
connection = engine.connect()
id_count = connection.execute('SELECT COUNT(DISTINCT(id)) FROM csv.agencies')
id_count
<sqlalchemy.engine.result.ResultProxy object at 0x10357d290>
Run Code Online (Sandbox Code Playgroud)