views:

182

answers:

1

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                                                       

#conn = psycopg2.connect("dbname='tkk' host='localhost' port='5432' user='noa' password='123'")

conn = psycopg2.connect("dbname=tk user=naa password=123")
cur = conn.cursor()
cur.execute("""INSERT INTO courses (course_nro)
            VALUES ( %(course_nro)s )""", dict(course_nro='abcd'))
conn.commit()

#2 Fetching

cur.execute("SELECT * FROM courses")
print cur.fetchall()

Examples about the two commands in SQLalchemy

insert

sqlalchemy.sql.expression.insert(table, values=None, inline=False, **kwargs)

select

sqlalchemy.sql.expression.select(columns=None, whereclause=None, from_obj=[], **kwargs)
+1  A: 

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 models
class Cource(DelcarativeBase):
    __tablename__ = 'courses'

    course_nro = Column('course_nro', CHAR(12))

This declarative method is just one way of using sqlalchemy.

MizardX