本文介绍了将SQL命令转换为Python的ORM的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将以下代码(例如通过SQLalchemy)转换为Python的ORM?

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提取

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

关于 SQLalchemy 中的两个命令的示例

插入

Examples about the two commands in SQLalchemy

insert

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

选择

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

推荐答案

在初始声明之后,您可以执行以下操作:

After the initial declarations, you can do something like this:

o = Course(course_nro='abcd')
session.add(o)
session.commit()

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))

这种声明性方法只是使用sqlalchemy的一种方法.

This declarative method is just one way of using sqlalchemy.

这篇关于将SQL命令转换为Python的ORM的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-21 10:20