DEV Community

tp1050
tp1050

Posted on

Working with existing DB Tables through Python

The whole point of coding is to not learn stuff and do things faster, no one codes because they want to learn some random framework by heart as if it was a religious book sent down by some divine power!

What is on the web?
Millions of Tutorials who insist on teaching DB interaction through creation of Tables and manipulation of DB via Python.
Reality--> A programmer needs a simple mechanism of inserting simple data units into an already existing Database or retrieving them back.

Managing the DB is in itself a vast academic field and almost always is handled by actual DB managed DUDE/Girl who has devoted his life to digital book keeping leaving those in the hands of a python coder is nothing short of insanity so it begs the question why is there so many tutorial on creating db via python and not enough simple ones about just retrieving the damn data!!! The only possible answer is deep sexual frustration and social anxieties of the IT community members who make such useless tutorials.

So if you need to access a table in the database that is already in there all you have to is to have this piece of code:

`

`from sqlalchemy import MetaData,create_engine
from sqlalchemy.orm import declarative_base, sessionmaker

import sqlalchemy

str1='mysql+pymysql://username:pass@ip_of_db:port_of_dbserver/schema_name'
engine=create_engine(str1)
s_factory=sessionmaker(bind=engine)
metadata = MetaData(engine)
metadata.reflect()
Base=declarative_base(metadata=metadata)

class Users(Base):
tablename='users'
tableargs={"autoload": True,"autoload_with":engine}

with s_factory() as s:
ret=s.query(Users).filter(Users.id==3).first()
print(ret)`

from sqlalchemy import MetaData,create_engine
from sqlalchemy.orm import declarative_base, sessionmaker

import sqlalchemy

str1='mysql+pymysql://username:pass@ip_of_db:port_of_dbserver/schema_name'
engine=create_engine(str1)
s_factory=sessionmaker(bind=engine)
metadata = MetaData(engine)
metadata.reflect()
Base=declarative_base(metadata=metadata)

class Users(Base):
tablename='users'
tableargs={"autoload": True,"autoload_with":engine}

with s_factory() as s:from sqlalchemy import MetaData,create_engine
from sqlalchemy.orm import declarative_base, sessionmaker

import sqlalchemy

str1='mysql+pymysql://username:pass@ip_of_db:port_of_dbserver/schema_name'
engine=create_engine(str1)
s_factory=sessionmaker(bind=engine)
metadata = MetaData(engine)
metadata.reflect()
Base=declarative_base(metadata=metadata)

class Users(Base):
tablename='users'
tableargs={"autoload": True,"autoload_with":engine}

with s_factory() as s:
ret=s.query(Users).filter(Users.id==3).first()
print(ret)
ret=s.query(Users).filter(Users.id==3).first()
print(ret)`
I bet on entirety my sexual hormones that this comment-less piece of code is more useful then the entire alchemy Doc on hand!!!

Top comments (0)