建立鏈接
# 參數: '數據庫類型+數據庫驅動名稱://用戶名:口令@機器地址:端口號/數據庫名'
from sqlalchemy import create_engine
engine = create_engine('mysql+mysqlconnector://root:password@localhost:3306/test')
# sqlite 是文件數據庫,鏈接方式不一樣
# sqlite://<nohostname>/<path>
engine = create_engine('sqlite:///foo.db')
# Unix/Mac
engine = create_engine('sqlite:////absolute/path/to/foo.db')
# windows
engine = create_engine(r'sqlite:///C:\path\to\foo.db')
engine = create_engine('sqlite:///C:\\path\\to\\foo.db')
表的建立
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(Integer, primary_key=True)
name = Column(String)
fullname = Column(String)
password = Column(String)
def __repr__(self):
return "<User(name='%s', fullname='%s', password='%s')>" % (
self.name, self.fullname, self.password)
# 建立表
Base.metadata.create_all(engine)
CRUD
建立 session
from sqlalchemy.orm import sessionmaker
DBSession = sessionmaker(bind=engine)
session = DBSession()
插入數據
# 插入單條記錄
ed_user = User(name='ed', fullname='Ed Jones', password='edspassword')
session.add(ed_user)
# 插入多條記錄
session.add_all([
User(name='wendy', fullname='Wendy Williams', password='foobar'),
User(name='mary', fullname='Mary Contrary', password='xxg527'),
User(name='fred', fullname='Fred Flinstone', password='blah')])
# 提交到數據庫
session.commit()
# 若是想要操做只是在內存中,不真正commit,ed_user.id 不爲None,可使用flush操做,它只是寫到內存中
session.flush()
更新
user.name = 'haha'
session.commit()
刪除
session.delete(user)