Converting Sql Commands To Python's Orm
How would you convert the following codes to Python's ORM such as by SQLalchemy? #1 Putting data to Pg import os, pg, sys, re, psycopg2
Solution 1:
After the initial declarations, you can do something like this:
o = Course(course_nro='abcd')
session.add(o)
session.commit()
and
print session.query(Course).all()
The declarations could look something like this:
from sqlalchemy import *
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import session_maker
# create an engine, and a base class
engine = create_engine('postgre://naa:123@localhost/tk')
DeclarativeBase = declarative_base(bind=engine)
metadata = DeclarativeBase.metadata
# create a session
Session = session_maker(engine)
session = Session()
# declare the modelsclassCource(DelcarativeBase):
__tablename__ = 'courses'
course_nro = Column('course_nro', CHAR(12))
This declarative method is just one way of using sqlalchemy.
Solution 2:
Even though this is old, more examples can't hurt, right? I thought I'd demonstrate how to do this with PyORMish.
from pyormish import Model
classCourse(Model):
_TABLE_NAME = 'courses'
_PRIMARY_FIELD = 'id'# or whatever your primary field is
_SELECT_FIELDS = ('id','course_nro')
_COMMIT_FIELDS = ('course_nro',)
Model.db_config = dict(
DB_TYPE='postgres',
DB_CONN_STRING='postgre://naa:123@localhost/tk'
)
To create:
new_course = Course().create(course_nro='abcd')
To select:
# return the firstrowWHERE course_nro='abcd'
new_course = Course().get_by_fields(course_nro='abcd')
Post a Comment for "Converting Sql Commands To Python's Orm"