1. 程式人生 > >DEVOPS02-pymysql模組應用 sqlalchemy和ORM sqlalchemy操作資料庫

DEVOPS02-pymysql模組應用 sqlalchemy和ORM sqlalchemy操作資料庫

一、PyMySQL模組

1.1 PyMySQL安裝

1.1.1 使用pypi

•  pypi即python package index
•  是python語言的軟體倉庫
•  官方站點為https://pypi.python.org

1.1.2 通過pip安裝PyMySQL模組

1. 安裝依賴包
[[email protected]    packages]# yum  install -y gcc
2. 本地安裝
[[email protected]

    packages]#    pip3    install    PyMySQL-0.8.0.tar.gz
3. 線上安裝
[[email protected]    packages]#    pip3    install    pymysql

1.1.3 使用國內映象站點

1. 為了實現安裝加速,可以配置pip安裝時採用國內映象站點

[[email protected]    ~]#    mkdir    ~/.pip/    
[[email protected]    ~]#    vim    ~/.pip/pip.conf        
[global]    
index-url=hKp://pypi.douban.com/simple/    
[install]    
trusted-host=pypi.douban.com    

1.2 PyMySQL應用

1.2.1 連線資料庫

1. 建立連線是訪問資料庫的第一步
conn    =    pymysql.connect(host='127.0.0.1',    port=3306,    user='root',    
passwd='tedu.cn',    db='tkq1',    charset='uU8')    

1.2.2 遊標

1. 遊標(cursor)就是遊動的標識
2.  通俗的說,一條sql取出對應n條結果資源的介面/控制代碼,就是遊標,沿著遊標可以一次取出一行

cursor    =    conn.cursor()

1.2.3 插入資料

1.對資料庫表做修改操作,必須要commit

import pymysql
conn=pymysql.connect(
    host='127.0.0.1',
    port=3306,
    user='root',
    passwd='123456',
    db='tarena1804',
    charset='utf8'
)

cursor=conn.cursor() #建立遊標
insert1 = 'INSERT INTO department VALUES (%s, %s)'
result1 = cursor.execute(insert1, (1, 'development'))
depts1 = [(2, 'operations'), (3, 'QA')]
depts2 = [(4, '人事部'), (5, '財務部')]
result2 = cursor.executemany(insert1, depts1)
result3 = cursor.executemany(insert1, depts2)

conn.commit()
cursor.close()
conn.close()

1.2.4 查詢資料

1. 可以取出表中一條、多條或全部記錄

import pymysql
conn=pymysql.connect(
    host='127.0.0.1',
    port=3306,
    user='root',
    passwd='123456',
    db='tarena1804',
    charset='utf8'
)

cursor=conn.cursor()   #建立遊標
query1='select * from department'
cursor.execute(query1)
data1=cursor.fetchone()    #查詢一條資料
print(data1)
print('*'*50)
data2=cursor.fetchmany(2)  #查詢多條資料
print(data2)
print('*'*50)
data3=cursor.fetchall()    #查詢所有資料
print(data3)

1.2.5 移動遊標

1. 從頭開始移動遊標用mode=“absolute”,從相對位置移動遊標可以使用mode=“relative”

cursor=conn.cursor()

query1='select * from department'
cursor.execute(query1)
cursor.scroll(1,'absolute')
data1=cursor.fetchone()
print(data1)
print('*'*50)
cursor.scroll(1)
data2=cursor.fetchone()
print(data2)

1.2.6 修改/刪除記錄

1.通過update/delete修改某一欄位的值

import pymysql
conn=pymysql.connect(
    host='127.0.0.1',
    port=3306,
    user='root',
    passwd='123456',
    db='tarena1804',
    charset='utf8'
)

cursor=conn.cursor()
update1='update department set dep_name=%s where dep_name=%s'
delete1='delete from department where dep_id=%s'
cursor.execute(update1,('人力資源','人事部',))
cursor.execute(delete1,(5,))
conn.commit()
cursor.close()
conn.close()

二、SQLAlchemy基礎

2.1 SQLAlchemy概述

2.1.1 SQLAlchemy安裝

SQLAlchemy由官方收錄,可以直接安裝
[[email protected]    packages]#    pip3    install    sqlalchemy

2.1.2 SQLAlchemy簡介

SQLAlchemy是一款通過物件關係對映去相容各種資料庫的開源軟體

2.1.3 SQLAlchemy架構

2.1.4 ORM模型

1. ORM即物件關係對映
2. 資料庫表是一個二維表,包含多行多列。把一個表的
內容用Python的資料結構表示出來的話,可以用一
個list表示多行,list的每一個元素是tuple,表示一行
記錄
[    
                ('1',    'Michael'),    
                ('2',    'Bob'),    
                ('3',    'Adam')    
]    

3.用tuple表示一行很難看出表的結構。如果把一個
tuple用class例項來表示,就可以更容易地看出表的
結構來
class    User(object):    
                def    __init__(self,    id,    name):    
                                self.id    =    id    
                                self.name    =    name    

2.2 資料庫物件管理

2.2.1 連線mysql

1. 通過create_engine實現資料庫的連線

from sqlalchemy import create_engine

engine=create_engine(
    'mysql+pymysql://root:[email protected]/tedu1804?charset=utf8',
    encoding='utf8',
    echo=True
)

2.2.2 宣告對映

1.在使用ORM的時候,首先需要定義基類

from sqlalchemy.ext.declarative import declarative_base
Base=declarative_base()   #生成ORM對映基類

2.2.3 建立對映類

from sqlalchemy	import Column,Integer,String	
class Department(Base):
    __tablename__='department'  #對應表名
    dep_id=Column(Integer,primary_key=True)  #dep_id欄位
    dep_name=Column(String(20),unique=True,nullable=False)

2.2.4 建立會話類

1. ORM需要建立會話類來訪問資料庫

from sqlalchemy.orm import sessionmaker
Session=sessionmaker(bind=engine)  #建立會話類,用於連線資料庫

2.2.5 外來鍵約束

dep_id=Column(Integer,ForeignKey('department.dep_id'))

2.2.6 通過ORM在資料庫中建立表

1.  建立employees表
2.  建立部門表
3.  建立salary表
4.  表間建立恰當的關係

from sqlalchemy import create_engine,Column,Integer,String,Date, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

engine=create_engine(
    'mysql+pymysql://root:[email protected]/tedu1804?charset=utf8',
    encoding='utf8',
    echo=True
)

Base=declarative_base()   #生成ORM對映基類
Session=sessionmaker(bind=engine)  #建立會話類,用於連線資料庫

class Department(Base):
    __tablename__='department'  #對應表名
    dep_id=Column(Integer,primary_key=True)  #dep_id欄位
    dep_name=Column(String(20),unique=True,nullable=False)

    def __str__(self):
        return '<部門: %s>' % self.dep_name

class Employee(Base):
    __tablename__ = 'employee'  # 對應表名
    emp_id=Column(Integer,primary_key=True)
    emp_name=Column(String(20),nullable=False)
    gender=Column(String(6))
    birth_date=Column(Date)
    phone=Column(String(11),unique=True)
    email=Column(String(50),unique=True)
    dep_id=Column(Integer,ForeignKey('department.dep_id'))

    # def __str__(self):
    #     return '<員工:%s>' % self.emp_name

class salary(Base):
    __tablename__ = 'salary'  # 對應表名
    autoid=Column(Integer,primary_key=True)
    emp_id=Column(Integer,ForeignKey('employee.emp_id'))
    date=Column(Date)
    basic=Column(Integer)
    awards=Column(Integer)

if __name__ == '__main__':
    Base.metadata.create_all(engine)

2.2.7 新增資料

1.  分別在部門表、員工表和工資表中加入資料
2.  通過SQLAlchemy程式碼實現
3.  應用SQLAlchemy每次一行資料和每次可加入多行資料

from dbconn import Department, Employee, Session

session=Session()
# dep_dev=Department(dep_name='department')
# dep_hr=Department(dep_name='人事部')
# dep_op=Department(dep_name='運維部')

wh = Employee(
    emp_name='王賀',
    gender='male',
    birth_date='1993-1-1',
    phone='17788990020',
    email='[email protected]',
    dep_id=1
)
lj = Employee(
    emp_name='李俊',
    gender='male',
    birth_date='1995-10-1',
    phone='15255667788',
    email='[email protected]',
    dep_id=3
)

zzh = Employee(
    emp_name='趙子浩',
    gender='male',
    birth_date='1999-5-4',
    phone='13656789987',
    email='[email protected]',
    dep_id=3
)

# session.add_all([dep_dev,dep_hr,dep_op])
session.add_all([wh, lj, zzh])
session.commit()
session.close()

三、 SQLAlchemy進階

3.1 查詢操作

3.1.1 基本查詢

1.通過session的query([args .. ])函式建立查詢物件

from dbconn import Session,Department,Employee

session=Session()
query1=session.query(Department)
print(query1)
for instance in query1:
    print(instance)   #取出的是每個部門的例項
print(query1[0].dep_id) #列印第一個部門的名稱
print('#'*40)

3.1.2 排序

1. 通過order_by()函式可以實現按指定欄位排序

2. 通過[start index: end index]實現資料的提取

query2=session.query(Department).order_by(Department.dep_id)[2:5]
print(query2)
for instance in query2:
    print(instance)

3.1.3 結果過濾

1. SQLAlchemy常用過濾操作符

1.1 相等
query.filter(Employees.name=='john')
1.2 不相等
query.filter(Employees.name!='john')
1.3 模糊查詢
query.filter(Employees.name.like(' %j '))

1.4 in
query.filter(new_emp.name.in_(['bob', 'john'])
1.5 not in
query.filter(~new_emp.name.in_(['bob', 'john'])
1.6 欄位為空
query.filter(new_emp.name.is_(None))
1.7 欄位不為空
query.filter(new_emp.name.isnot(None))

1.8 多重條件and
from sqlalchemy import and_
query.filter(and_(new_sal.basic>=10000,
new_sal.extra>=2000))
1.9 多重條件or
from sqlalchemy import or_
query.filter(or_(new_sal.basic>=10000,
new_sal.extra>=3000))

1.10 filter()函式可以疊加使用

query3=session.query(Department).filter(Department.dep_id>2).filter(Department.dep_id<4)
print(query7)
for dep in query7:
    print(dep)

3.1.4 查詢物件返回值

•  all()返回列表
•  first()返回結果中的第一條記錄
•  one()取出所有記錄,如果不是一條記錄則丟擲異常
•  scalar()呼叫one(),返回第一列的值

3.1.5 聚合

1.通過count()方法,統計行數

print(session.query(Departments).count())

3.1.6 多表查詢

1. 通過join()方法實現多表查詢

q = session.query(Employees.name, Departments.dep_name).join(Departments,
Employees.dep_id==Departments.dep_id )    
print(q.all())    

3.2 修改操作

3.2.1 更新資料

1. 通過session的update()方法更新

from dbconn import Session,Department

session=Session()

q1=session.query(Department).filter(Department.dep_id==1)
for i in q1:
    print(i)
q1.update({Department.dep_name:'技術部'})
session.commit()
session.close()

2. 通過會話的欄位賦值更新

from dbconn import Session,Department

session=Session()
q2=session.query(Department).get(1)
print(q2)
q2.dep_name='department'
session.commit()
session.close()

3.3 刪除記錄

1. 通過會話的delete()方法進行記錄刪除

from dbconn import Session,Department

session=Session()
q2=session.query(Department).get(2)
session.delete(q1)    
session.commit()    
session.close()