sqlalchmey orm中的crud函数

时间:2019-03-11 10:19:21

标签: python-3.x orm sqlalchemy

所以我试图在我的代码上实现CRUD函数,所以我试图先创建一个会话,但是它一直给我一个错误“未定义引擎”,所以我尝试定义它,但我一直遇到相同的错误。该代码使用sqlalchemy ORM创建3个表(用户,帐户,位置)的数据库。我在做什么错了?

from sqlalchemy import create_engine, Column, Integer, Boolean, String, ForeignKey, DateTime
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy.orm import sessionmaker
from sqlalchemy.orm.query.Query


Session = sessionmaker(bind=engine)

Base = declarative_base()


class User(Base):
    __tablename__ = "user"
    id = Column('id',Integer,primary_key=True , autoincrement=True)
    username = Column('username',String , unique=True)
    admin = Column('admin',Boolean )
    password = Column('password' , String)      
    email = Column('email' , String , unique=True)
    p_id = Column(Integer , ForeignKey('place.id'))
    googleassist = Column('googleassist' , String)      
    account = relationship("Account",           ## Cascade to delete associated account
        back_populates='user',          ## if that user was deleted.
        cascade='all, delete-orphan')


class Account(Base):
    __tablename__ = "account"
    id = Column('id', Integer,primary_key=True,autoincrement=True)
    user_id = Column(Integer , ForeignKey('user.id'))



class Place(Base):
    __tablename__ = "place"
    id = Column('id', Integer,primary_key=True,autoincrement=True)
    p_location = Column('p_location' , String)
    h_id = Column('h_id',Integer)


Session.configure(bind=engine)
engine = create_engine('sqlite:///withServer.db')
Base.metadata.create_all(engine)

session = Session(engine)
#creating objects

u1=User(    id = '1' ,
              username = 'ali',
              admin = '1',
              password = 'pass',
              email = 'haifa@gmail.com'
              )
session.add(u1)
session.commit()


#update
i = session.query(User)
i.password = 'passtoo'
session.add(i)
session.commit()


#delete
i = session.query(Account).filter(Account.id == '1').one()
session.delete(i)
session.commit()

1 个答案:

答案 0 :(得分:0)

实际上,您仅使用engine而不先定义它:

Session = sessionmaker(bind=engine)

您需要在该行之前输入engine的定义。

engine = create_engine('sqlite:///withServer.db')

在第一次使用engine之前。