SQLALchemy操作MySQL關係型資料庫

Winter發表於2019-05-07

1.SQLALchemy使用

  • 安裝

pip install sqlalchemy;

  • SQLAlchemy是Python程式語言下的一款開源軟體,是PythonSQL工具包和物件關係對映器,它為應用程式開發人員提供了SQL的全部功能和靈活性

2.什麼是ORM

  • ORM(Object Relational Mapper)就是把資料庫表的行與相應的物件建立關聯,互相轉換;

  • 目前,最知名的Python ORM是SQLAlchemy和SQLobject;

3.資料庫操作

  • 建立表 使用 create_all() 方法, 刪除表 使用 drop_all() 方法,我們一起來看一下如何建立和刪除表

# 匯入引擎模組
from sqlalchemy import create_engine
# 匯入基類模組
from sqlalchemy.ext.declarative import declarative_base
# 匯入欄位類
from sqlalchemy import Column, Integer, String
# 匯入會話模組
from sqlalchemy.orm import sessionmaker
# 實體類的基類
Base = declarative_base()
# 實體類
class Teacher(Base):
    '''
    實體類的建立有兩個方面的用處:
    1:如果資料庫中沒有表,那麼可以使用實體類建立
    2:如果資料庫中有表,實體類可以對映表的結構,對錶的CRUD操作
    '''
    # 表名必須指定
    __tablename__ = 'teacher'
    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String(255))
    age = Column(Integer)
    # 列印例項的使用可以發現,資料也是儲存在實體類例項的__dict__中
    def __repr__(self):
        # print(self.__dict__)
        return "id='%s', name='%s', age='%s" % (self.id, self.name, self.age)
    __str__ = __repr__
# 建立連線引擎
host = 'localhost'
port = 3306
username = 'zengzeng'
password = '123456'
db = 'XKD_Python_Course'
connect_str = 'mysql+mysqldb://{}:{}@{}:{}/{}'.format(username, password, host, port,db)
engine = create_engine(connect_str, echo=True)
# 建立表
Base.metadata.create_all(engine)
# 刪除表
# Base.metadata.drop_all(engine)

我們現在命令工具中檢視一下資料庫中有沒有我們想要的teacher表,上一篇文章中講過,先登入mysql: mysql -uzengzeng -p123456 ,然後進入我們要使用的資料庫: use XKD_Python_Course ,我們先通過: show tables; 檢視一下資料庫中的表,發現沒有teacher表
那現在就可以執行程式碼,建立資料庫了,建立好後我們可以在命令列檢視一下: show tables; ,發現teacher表已經存在了,建立表成功yes!

檢視錶

想要刪除剛剛建立的表,可以使用 drop_all() 方法,執行程式碼,再檢視資料庫表,就可以看teacher表已經被刪除了


Base.metadata.drop_all(engine)

  • 插入資料 使用 session.add_all() 方法;

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import sessionmaker
Base = declarative_base()
class Teacher(Base):
    __tablename__ = 'teacher'
    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String(255))
    age = Column(Integer)
    def __repr__(self):
        # print(self.__dict__)
        return "id='%s', name='%s', age='%s" % (self.id, self.name, self.age)
    __str__ = __repr__
host = 'localhost'
port = 3306
username = 'zengzeng'
password = '123456'
db = 'XKD_Python_Course'
connect_str = 'mysql+mysqldb://{}:{}@{}:{}/{}'.format(username, password, host, port,db)
engine = create_engine(connect_str, echo=True)
# 建立會話,用於提交資料
Session = sessionmaker(bind=engine)
session = Session()
# 建立多行行例項,給表新增資料
try:
    lst = []
    for i in range(10):
        teacher = Teacher()
        teacher.name = 'zengzeng' + str(i)
        teacher.age = 20 + i
        lst.append(teacher)
        print(teacher)
    # session.add(student) 可以新增一行記錄,也可以新增多行記錄
    # 注意:這裡將行記錄例項新增到session,不會提交,需要手動提交
    session.add_all(lst)
except Exception as e:
    print('~~~~~~~~~~~'*200)
    session.rollback()
    print(e)
finally:
    session.commit()

我們執行程式碼,然後去命令工具檢視一下表是否插入資料: select * from teacher;

插入資料

  • 查詢操作 使用 session.query() 方法,迭代查詢;

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import sessionmaker
Base = declarative_base()
class Teacher(Base):
    __tablename__ = 'teacher'
    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String(255))
    age = Column(Integer)
    def __repr__(self):
        # print(self.__dict__)
        return "id='%s', name='%s', age='%s" % (self.id, self.name, self.age)
    __str__ = __repr__
host = 'localhost'
port = 3306
username = 'zengzeng'
password = '123456'
db = 'XKD_Python_Course'
conn_str = 'mysql+mysqldb://{}:{}@{}:{}/{}'.format(username, password, host, port,db)
engine = create_engine(conn_str, echo=False)
Session = sessionmaker(bind=engine)
session = Session()
teacher_obj = session.query(Teacher)
for teacher in  teacher_obj:
    print(teacher) # 返回結果:{'_sa_instance_state': <sqlalchemy.orm.state.InstanceState object at 0x1063125f8>, 'age': 20, 'name': 'nihao0', 'id': 1}
print('*'*300)
# 直接返回例項物件
teacher = session.query(Teacher).get(4)
print(teacher) # 返回結果:{'_sa_instance_state': <sqlalchemy.orm.state.InstanceState object at 0x1075fd400>, 'age': 23, 'name': 'nihao3', 'id': 4}
print(teacher.id)  # 返回 aobama
print(teacher.name)
print(teacher.age)
print('*'*300)
# 返回的是可迭代物件
teacher_results = session.query(Teacher).filter(Teacher.id == 5)
for teacher in teacher_results:  # 拿到student例項物件
    print(teacher)

  • 修改操作: session.update()

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String
from sqlalchemy.orm import sessionmaker
Base = declarative_base()
class Teacher(Base):
    __tablename__ = 'teacher'
    id = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String(255))
    age = Column(Integer)
    def __repr__(self):
        # print(self.__dict__)
        return "id='%s', name='%s', age='%s" % (self.id, self.name, self.age)
    __str__ = __repr__
# 建立連線引擎
host = 'localhost'
port = 3306
username = 'zengzeng'
password = '123456'
db = 'XKD_Python_Course'
conn_str = 'mysql+mysqldb://{}:{}@{}:{}/{}'.format(username, password, host, port,db)
engine = create_engine(conn_str, echo=False)
# 建立會話,用於提交資料
Session = sessionmaker(bind=engine)
session = Session()
teacher = session.query(Teacher).get(4)
teacher.name = 'Robby'
teacher.age = '99'
session.commit()

where條件查詢


from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, DATE, Enum, ForeignKey
import enum
from sqlalchemy.orm import sessionmaker
Base = declarative_base()
class My_Enum(enum.Enum):
    M = 'M'
    F = 'F'
# 實體類
class Emploee(Base):
    '''
    +------------+---------------+------+-----+---------+-------+
    | Field      | Type          | Null | Key | Default | Extra |
    +------------+---------------+------+-----+---------+-------+
    | emp_no     | int(11)       | NO   | PRI | NULL    |       |
    | birth_date | date          | NO   |     | NULL    |       |
    | first_name | varchar(14)   | NO   |     | NULL    |       |
    | last_name  | varchar(16)   | NO   |     | NULL    |       |
    | gender     | enum('M','F') | NO   |     | NULL    |       |
    | hire_date  | date          | NO   |     | NULL    |       |
    +------------+---------------+------+-----+---------+-------+
    '''
    __tablename__ = 'employees'
    emp_no = Column(Integer, primary_key=True, nullable=False)
    birth_date = Column(DATE, nullable=False)
    first_name = Column(String(14), nullable=False)
    last_name = Column(String(16),nullable=False)
    gender = Column(Enum(My_Enum), nullable=False)
    hire_date = Column(DATE, nullable=False)
    def __repr__(self):
        return "emp_no='%s', birth_date='%s', first_name='%s', last_name='%s', gender='%s', hire_date='%s'" % (self.emp_no, self.birth_date, self.first_name, self.last_name, self.gender, self.hire_date)
    __str__ = __repr__
# 建立連線引擎
host = 'localhost'
port = 3306
username = 'zengzeng'
password = '123456'
db = 'XKD_Python_Course'
conn_str = 'mysql+mysqldb://{}:{}@{}:{}/{}'.format(username, password, host, port,db)
engine = create_engine(conn_str, echo=False)
# 建立表
Base.metadata.create_all(engine)
# 建立會話,用於提交資料
Session = sessionmaker(bind=engine)
session = Session()
# # 簡單的where條件查詢過濾, 返回可迭代物件, AND 取與
emploees = session.query(Emploee).filter(Emploee.emp_no < 10010).filter(Emploee.gender == 'M')
emploees = session.query(Emploee).filter((Emploee.emp_no > 10010) & (Emploee.gender == 'F'))
# OR 取並
emploees = session.query(Emploee).filter((Emploee.emp_no > 10010) | (Emploee.gender == 'F'))
# NOT 取反
emploees = session.query(Emploee).filter(~(Emploee.emp_no > 10010))
# in
emploees = session.query(Emploee).filter(Emploee.emp_no.in_([10010, 10011, 10012]))
# not in
emploees = session.query(Emploee).filter(~Emploee.emp_no.in_([10010, 10011, 10012]))
# like ,like可以忽略大小寫進行模式匹配
emploees = session.query(Emploee).filter(Emploee.last_name.like('B%'))
for emploee in emploees:
    print(emploee)

order排序

  • asc() :升序;

例如:
emploees = session.query(Emploee).filter(Emploee.last_name.like('B%')).order_by(Emploee.emp_no.asc())

  • desc() :降序;

例如:
emploees=session.query(Emploee).filter(Emploee.last_name.like('B%')).order_by(Emploee.emp_no.desc())

  • 多欄位排序:在語句裡面進行多次排序;

聚合與分組

  • list() :轉化為列表;

  • count() :聚合count(*)查詢;

  • all() : 轉化為列表;

  • limit().one() :查詢首行;

    
    emploees = session.query(Emploee)
    print(list(emploees))         # 轉化為列表
    print(emploees.count())     # 聚合count(*)查詢
    print(emploees.all())        # 轉化為列表
    print(emploees.limit(1).one())    # 查詢首行
    
    
  • max() :返回最大值;

  • min() :返回最小值;

  • avg() :返回平均值;

    
    emploees = session.query(func.max(Emploee.emp_no))
    emploees = session.query(func.min(Emploee.emp_no))
    emploees = session.query(func.avg(Emploee.emp_no))
    
    
  • group_by() :分組查詢;


emploees = session.query(func.count(Emploee.emp_no)).group_by(Emploee.gender)
print(emploees)
for emploee in emploees:
    print(emploee)

參考: https://www.9xkd.com/user/plan-view.html?id=2415909403

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69908432/viewspace-2643540/,如需轉載,請註明出處,否則將追究法律責任。

相關文章