Vivek Kumar
Vivek Kumar

Reputation: 189

How to fetch existing table from database using sqlalchemy in python?

I have 'device' table in my database, I am trying to fetch the that device object so i can update some record to that table . I have tried meta = MetaData(bind=engine, reflect=True) its working fine but showing some warning "SADeprecationWarning: The MetaData.reflect flag is deprecated and will be removed in a future release. Please use the MetaData.reflect() method." When i am trying with MetaData.reflect() not getting the expected output .

from sqlalchemy import create_engine, inspect
from sqlalchemy.orm import sessionmaker
from sqlalchemy.engine.url import URL
from sqlalchemy import MetaData

db_url = {
         'drivername': 'postgres',
          'username': 'postgres',
          'password': '***',
          'host': 'localhost',
        'database': "test_db",
          'port': 5432}
engine = create_engine(URL(**db_url))
session_obj = sessionmaker(bind=engine)
meta = MetaData().reflect(bind=engine)
print(meta)
user_t = meta.tables['device']
sel_st = user_t.select()
conn = engine.connect()
res = conn.execute(sel_st)
for _row in res:
    print(_row)

Let me know what i am missing .

Upvotes: 1

Views: 976

Answers (1)

xariasu
xariasu

Reputation: 21

change this line

meta = MetaData().reflect(bind=engine)
print(meta)
user_t = meta.tables['device']

into

meta = MetaData()
meta.reflect(bind=engine)
user_t= meta.tables.get('device')

Upvotes: 2

Related Questions