怎样在SQLAlchemy中执行SQL语句

新建SQLAlchemy的Engine

引入相关库

import sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy import Table, Column, Integer, String, MetaData, ForeignKey
from sqlalchemy import inspect

创建engine

engine = create_engine('postgresql://user:password@host/database')

执行SQL语句

with engine.connect() as con:

    rs = con.execute('SELECT * FROM book')

    for row in rs:
        print row

Out[*]:
(4, u'The Hobbit', u'Tolkien')
(5, u'The Silmarillion', u'Tolkien')

第二种方法

from sqlalchemy import text

# write the SQL query inside the text() block
sql = text('SELECT * from BOOKS WHERE BOOKS.book_price > 50')
results = engine.execute(sql)

# View the records
for record in results:
    print("\n", record)

获取列名的办法

如下book是表名

inspector = inspect(engine)
inspector.get_columns('book')

Out[*]:
[{'autoincrement': True,
  'default': None,
  'name': u'id',
  'nullable': False,
  'primary_key': 1,
  'type': INTEGER()},
 {'autoincrement': True,
  'default': None,
  'name': u'title',
  'nullable': True,
  'primary_key': 0,
  'type': VARCHAR()},
 {'autoincrement': True,
  'default': None,
  'name': u'primary_author',
  'nullable': True,
  'primary_key': 0,
  'type': VARCHAR()}]

参考文章:

Leave a Comment