2014년 8월 28일 목요일

sqlalchemy table autoload

http://www.blog.pythonlibrary.org/2010/09/10/sqlalchemy-connecting-to-pre-existing-databases/
http://stackoverflow.com/questions/6473925/sql-alchemy-getting-a-list-of-tables

#!/usr/bin/env python
# -*- coding: utf-8 -*-
#-------------------------------------------------------------------------------
from sqlalchemy import create_engine, MetaData, Table
from sqlalchemy.sql import select

import urllib
#-------------------------------------------------------------------------------
def test_autoload():
    engine = create_engine("mssql+pyodbc://%s:%s@%s:%d/%s" % (user_id, urllib.quote_plus(user_pw), db_ip, db_port, db_name), echo=True)
    conn = engine.connect()

    metadata = MetaData(engine)

    if 0:
        tbl_1 = Table("table_1", metadata, autoload=True)
        tbl_2 = Table("table_2", metadata, autoload=True)
    else:
        metadata.reflect(engine)

        print metadata.tables.keys()

        tbl_1 = metadata.tables["table_1"]
        tbl_2 = metadata.tables["table_2"]

    print tbl_1.columns
    print tbl_2.columns

    s = select([tbl_1, tbl_2]).where(tbl_1.c.user_id == tbl_2.c.sender_id)
    result = conn.execute(s)

    for row in result:
        print row
#-------------------------------------------------------------------------------
if __name__ == "__main__":
    test_autoload()

댓글 없음: