【Python之路】第十九篇--Python操做MySQL

本篇對於Python操做MySQL主要使用兩種方式:html

  • 原生模塊 pymsqlpython

  • ORM框架 SQLAchemymysql

pymsql

pymsql是Python中操做MySQL的模塊,其使用方法和MySQLdb幾乎相同。sql

下載安裝數據庫

pip3 install pymysql

使用操做編程

一、執行SQLsession

# 建立鏈接
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123456', db='db1',charset='utf8')
# 建立遊標
cursor = conn.cursor()

# 執行SQL,並返回受影響行數
effect_row = cursor.execute("update hosts set host = '1.1.1.2' where nid > %s", (1,))
  
# 執行SQL,並返回受影響行數
effect_row = cursor.executemany("insert into hosts(host,color_id)values(%s,%s)", [("1.1.1.11",1),("1.1.1.11",2)])

# 提交,否則沒法保存新建或者修改的數據
conn.commit()
  
# 關閉遊標
cursor.close()
# 關閉鏈接
conn.close()

增,刪,改須要執行 conn.commit()oracle

二、獲取新建立數據自增ID框架

import pymysql
  
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='t1')
cursor = conn.cursor()
cursor.executemany("insert into hosts(host,color_id)values(%s,%s)", [("1.1.1.11",1),("1.1.1.11",2)])
conn.commit()
cursor.close()
conn.close()
  
# 獲取最新自增ID  => 若是插入多條,只能拿到最後一條id
new_id = cursor.lastrowid

三、獲取查詢數據編程語言

import pymysql
  
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='t1')
cursor = conn.cursor()
cursor.execute("select * from hosts")
  
# 獲取第一行數據
row_1 = cursor.fetchone()
# => 再次執行:cursor.fetchone() 得到下一條數據,沒有時爲None

# 獲取前n行數據
# row_2 = cursor.fetchmany(n)
# ==> 執行了n次fetchone()

# 獲取全部數據
# row_3 = cursor.fetchall()
  
conn.commit()
cursor.close()
conn.close()

注:在fetch數據時按照順序進行,可使用cursor.scroll(num,mode)來移動遊標位置,如:

  • cursor.scroll(-1,mode='relative')  # 相對當前位置移動

  • cursor.scroll(2,mode='absolute') # 相對絕對位置移動

四、fetch數據類型

  關於默認獲取的數據是元祖類型,若是想要或者字典類型的數據,即:

import pymysql
  
conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123456', db='t1')
  
# 遊標設置爲字典類型
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

row = cursor.execute("select * from user")
  
result = cursor.fetchone()
print(result)

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

補充:

1.SQL注入

因爲字符串拼接出現注入
"select name from user where name='%s' and password ='%s' " %(username,password)
pymysql 提供了轉義功能:
"select name from user where name=%s and password =%s ",( username,password ) 

SQLAchemy

SQLAlchemy是Python編程語言下的一款ORM框架,該框架創建在數據庫API之上,使用關係對象映射進行數據庫操做,

簡言之即是:將對象轉換成SQL,而後使用數據API執行SQL並獲取執行結果。

ORM:

ORM框架的做用就是把數據庫表的一行記錄與一個對象互相作自動轉換。 正確使用ORM的前提是瞭解關係數據庫的原理。

ORM就是把數據庫表的行與相應的對象創建關聯,互相轉換。 因爲關係數據庫的多個表還能夠用外鍵實現一對多、多對多等關聯,

相應地, ORM框架也能夠提供兩個對象之間的一對多、多對多等功能。

SQLAlchemy:

自己沒法操做數據庫,其必須以pymsql等第三方插件,

Dialect用於和數據API進行交流,根據配置文件的不一樣調用不一樣的數據庫API,從而實現對數據庫的操做,如:

MySQL-Python
    mysql+mysqldb://<user>:<password>@<host>[:<port>]/<dbname>
  
pymysql
    mysql+pymysql://<username>:<password>@<host>/<dbname>[?<options>]
  
MySQL-Connector
    mysql+mysqlconnector://<user>:<password>@<host>[:<port>]/<dbname>
  
cx_Oracle
    oracle+cx_oracle://user:pass@host:port/dbname[?key=value&key=value...]
  
更多詳見:http://docs.sqlalchemy.org/en/latest/dialects/index.html
#!/usr/bin/env python
# -*-coding:utf-8 -*-

from sqlalchemy import create_engine,and_,or_,func,Table
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String,ForeignKey
from  sqlalchemy.orm import sessionmaker,relationship

engine = create_engine("mysql+pymysql://root:123456@127.0.0.1:3306/t1?charset=utf8", max_overflow=5)

Base = declarative_base()


def init_db():
    Base.metadata.create_all(engine)   

def drop_db():
    Base.metadata.drop_all(engine)    

1、底層處理

使用 Engine/ConnectionPooling/Dialect 進行數據庫操做,Engine使用ConnectionPooling鏈接數據庫,而後再經過Dialect執行SQL語句。

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from sqlalchemy import create_engine
 
 
engine = create_engine("mysql+pymysql://root:123@127.0.0.1:3306/t1", max_overflow=5)
 
# 執行SQL
# cur = engine.execute(
#     "INSERT INTO hosts (host, color_id) VALUES ('1.1.1.22', 3)"
# )
 
# 新插入行自增ID
# cur.lastrowid
 
# 執行SQL
# cur = engine.execute(
#     "INSERT INTO hosts (host, color_id) VALUES(%s, %s)",[('1.1.1.22', 3),('1.1.1.221', 3),]
# )
 
 
# 執行SQL
# cur = engine.execute(
#     "INSERT INTO hosts (host, color_id) VALUES (%(host)s, %(color_id)s)",
#     host='1.1.1.99', color_id=3
# )
 
# 執行SQL
# cur = engine.execute('select * from hosts')
# 獲取第一行數據
# cur.fetchone()
# 獲取第n行數據
# cur.fetchmany(3)
# 獲取全部數據
# cur.fetchall()
View Code

2、ORM功能使用

使用 ORM/Schema Type/SQL Expression Language/Engine/ConnectionPooling/Dialect 全部組件對數據進行操做。

根據類建立對象,對象轉換成SQL,執行SQL。處理中文數據時,在鏈接數據庫時要加上   ?charset=utf8

1.建立表

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy import create_engine

engine = create_engine("mysql+pymysql://root:123@127.0.0.1:3306/t1", max_overflow=5)

Base = declarative_base()

# 建立單表
class Users(Base):

    __tablename__ = 'users'

    id = Column(Integer, primary_key=True)
    name = Column(String(32))
    extra = Column(String(16))

    # 設置索引:
    __table_args__ = (
    UniqueConstraint('id', 'name', name='uix_id_name'),
        Index('ix_id_name', 'name', 'extra'),
    )

    # 輸出Users對象時,調用:
    def __repr__(self):
        return "%s-%s-%s" % (self.id, self.name , self.extra)


def init_db():
    Base.metadata.create_all(engine)   #建立表 

def drop_db():
    Base.metadata.drop_all(engine)    #刪除表 
View Code

一對多

# 一對多
class Favor(Base):
    __tablename__ = 'favor'
    nid = Column(Integer, primary_key=True)
    caption = Column(String(50), default='red', unique=True)


class Person(Base):
    __tablename__ = 'person'
    nid = Column(Integer, primary_key=True)
    name = Column(String(32), index=True, nullable=True)
    favor_id = Column(Integer, ForeignKey("favor.nid"))   # 外鍵
View Code

多對多

# 多對多
class Group(Base):
    __tablename__ = 'group'
    id = Column(Integer, primary_key=True)
    name = Column(String(64), unique=True, nullable=False)
    port = Column(Integer, default=22)


class Server(Base):
    __tablename__ = 'server'

    id = Column(Integer, primary_key=True, autoincrement=True)
    hostname = Column(String(64), unique=True, nullable=False)


class ServerToGroup(Base):
    __tablename__ = 'servertogroup'
    nid = Column(Integer, primary_key=True, autoincrement=True)
    server_id = Column(Integer, ForeignKey('server.id'))
    group_id = Column(Integer, ForeignKey('group.id'))
View Code

2.操做表

#!/usr/bin/env python
# -*- coding:utf-8 -*-
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index
from sqlalchemy.orm import sessionmaker, relationship
from sqlalchemy import create_engine

engine = create_engine("mysql+pymysql://root:123@127.0.0.1:3306/t1", max_overflow=5)

#生成一個SQLORM基類
Base = declarative_base()

# 建立單表
class Users(Base):
    __tablename__ = 'users'
    id = Column(Integer, primary_key=True)
    name = Column(String(32))
    extra = Column(String(16))

    __table_args__ = (
    UniqueConstraint('id', 'name', name='uix_id_name'),
        Index('ix_id_name', 'name', 'extra'),
    )

    def __repr__(self):
        return "%s-%s" %(self.id, self.name)

# 一對多
class Favor(Base):
    __tablename__ = 'favor'
    nid = Column(Integer, primary_key=True)
    caption = Column(String(50), default='red', unique=True)

    def __repr__(self):
        return "%s-%s" %(self.nid, self.caption)

class Person(Base):
    __tablename__ = 'person'
    nid = Column(Integer, primary_key=True)
    name = Column(String(32), index=True, nullable=True)
    favor_id = Column(Integer, ForeignKey("favor.nid"))
    # 與生成表結構無關,僅用於查詢方便
    favor = relationship("Favor", backref='pers')

# 多對多
class ServerToGroup(Base):
    __tablename__ = 'servertogroup'
    nid = Column(Integer, primary_key=True, autoincrement=True)
    server_id = Column(Integer, ForeignKey('server.id'))
    group_id = Column(Integer, ForeignKey('group.id'))
    group = relationship("Group", backref='s2g')
    server = relationship("Server", backref='s2g')

class Group(Base):
    __tablename__ = 'group'
    id = Column(Integer, primary_key=True)
    name = Column(String(64), unique=True, nullable=False)
    port = Column(Integer, default=22)
    # group = relationship('Group',secondary=ServerToGroup,backref='host_list')


class Server(Base):
    __tablename__ = 'server'

    id = Column(Integer, primary_key=True, autoincrement=True)
    hostname = Column(String(64), unique=True, nullable=False)



def init_db():
    Base.metadata.create_all(engine)


def drop_db():
    Base.metadata.drop_all(engine)

# 這兩行觸發sessionmaker類下的__call__方法,return獲得 Session實例,賦給變量session,
# 因此session能夠調用Session類下的add,add_all等方法

Session = sessionmaker(bind=engine)
session = Session()
View Code

.增

obj = Users(name="alex0", extra='sb')
session.add(obj)
session.add_all([
    Users(name="alex1", extra='sb'),
    Users(name="alex2", extra='sb'),
])

session.commit()
View Code

.刪

session.query(Users).filter(Users.id > 2).delete()
session.commit()
View Code

.改

session.query(Users).filter(Users.id > 2).update({"name" : "099"})
session.query(Users).filter(Users.id > 2).update({Users.name: Users.name + "099"}, synchronize_session=False)
session.query(Users).filter(Users.id > 2).update({"num": Users.num + 1}, synchronize_session="evaluate")
session.commit()
View Code

.查

ret = session.query(Users).all()
ret = session.query(Users.name, Users.extra).all()
ret = session.query(Users).filter_by(name='alex').all()
ret = session.query(Users).filter_by(name='alex').first()
View Code

3.更多查詢方法:

#!/usr/bin/env python
# -*-coding:utf-8 -*-


from sqlalchemy import create_engine,and_,or_,func,Table
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String,ForeignKey
from  sqlalchemy.orm import sessionmaker,relationship


engine = create_engine('mysql+pymysql://root@127.0.0.1:3307/day40?charset=utf8')

Base = declarative_base()

class Man_To_Woman(Base):

    __tablename__ = 'man_to_woman'
    nid = Column(Integer,primary_key=True)
    man_id = Column(Integer,ForeignKey('man.nid'))
    woman_id = Column(Integer,ForeignKey('woman.nid'))

class Man(Base):

    __tablename__ = 'man'
    nid = Column(Integer,primary_key=True)
    name = Column(String(20),nullable=False)
    woman = relationship("Woman", secondary=Man_To_Woman.__table__)

class Woman(Base):

    __tablename__ = 'woman'
    nid = Column(Integer,primary_key=True)
    name = Column(String(20),nullable=False)
    man = relationship("Man",secondary=Man_To_Woman.__table__)



Base.metadata.create_all(engine)

MySession = sessionmaker(engine)
session = MySession()
事例: 表結構

1.filter_by( ... )  填寫鍵值對方式

ret = session.query(Man).filter_by(name='alex').first()
print(ret.nid,ret.name)

2.filter    填寫條件判斷

ret = session.query(Man).filter(Man.name=='eric').first()

ret = session.query(Man).filter(Man.name=='eric' , Man.nid > 0).first()

row = session.query(Man).filter(Man.nid.between(1,4)).all()

ret = session.query(Users).filter(Users.id.in_(session.query(Users.id).filter_by(name='eric'))).all()

3.and_  or_  條件判斷

from sqlalchemy import and_, or_

ret = session.query(Man).filter(and_(Man.name == 'eric',Man.nid == 2)).first()
ret = session.query(Man).filter(or_(Man.name == 'eric',Man.nid == 2)).first()

4.~   取反

ret = session.query(Man).filter(Man.nid.in_([2,3])).first()
ret = session.query(Man).filter(~Man.nid.in_([2,3])).first()

5.like + %   通配符

ret = session.query(Man).filter(Man.name.like('%x')).first()
ret = session.query(Man).filter(~Man.name.like('%x')).first()

6.切片  限制 ( 序號,前閉後開 )

row = session.query(Man)[1:3]
for ret in row:
    print(ret.nid, ret.name)

row = session.query(Man).limit(3).offset(1)

7.order_by   排序

row = session.query(Man).order_by(Man.nid.desc()).all()
row = session.query(Man).order_by(Man.nid.asc()).all()

8.group_by  分組

row = session.query(func.count('*')).select_from(Man).all()
row = session.query(func.count('*')).filter(Man_To_Woman.nid > 1).all()
row = session.query(func.count('*')).select_from(Man_To_Woman).group_by(Man_To_Woman.man_id).all()
row = session.query(func.count('*')).select_from(Man_To_Woman).group_by(Man_To_Woman.man_id).limit(1).all()

row = session.query(Man_To_Woman).group_by(Man_To_Woman.man_id).all()

ret = session.query(Users).group_by(Users.extra).all()
ret = session.query(
    func.max(Users.id),
    func.sum(Users.id),
    func.min(Users.id)).group_by(Users.name).all()

ret = session.query(
    func.max(Users.id),
    func.sum(Users.id),
    func.min(Users.id)).group_by(Users.name).having(func.min(Users.id) >2).all()

9.join  連表

row = session.query(Users, Favor).filter(Users.id == Favor.nid).all()

ret = session.query(Son).join(Father).all()

ret = session.query(Son).join(Father, isouter=True).all()

10.union  組合

q1 = session.query(Users.name).filter(Users.id > 2)
q2 = session.query(Favor.caption).filter(Favor.nid < 2)
ret = q1.union(q2).all()

q1 = session.query(Users.name).filter(Users.id > 2)
q2 = session.query(Favor.caption).filter(Favor.nid < 2)
ret = q1.union_all(q2).all()

更多功能參見文檔,猛擊這裏下載PDF

補充  Relationship:

  • 改變數據輸出的方式:能夠在表的類中定義一個特殊成員:__repr__, return一個自定義的由字符串拼接的數據鏈接方式.

  • 數據庫中表關係之間除了MySQL中標準的外鍵(ForeignKey)以外,還能夠建立一個虛擬的關係,好比 group = relationship("Group",backref='uuu'),通常此虛擬關係與foreignkey一塊兒使用.

relationship : 經過relatioinship 找到綁定關係的數據 !!!

一對多,連表操做:

class Father(Base):

    __tablename__ ='father'
    nid = Column(Integer,primary_key=True)
    name = Column(String(32))
    son = relationship('Son')


class Son(Base):

    __tablename__ = 'son'
    nid = Column(Integer, primary_key=True)
    name = Column(String(32))
    father_id = Column(Integer,ForeignKey('father.nid'))
    father = relationship('Father')
表結構

正向查詢:

需求:查詢Son表中全部數據,而且顯示對應的Father表中的數據.

ret = session.query(Son).all()
for obj in ret:
    print(obj.nid,obj.name,obj.father_id,obj.father.name)

反向查詢:

需求:查詢Father表中, 屬於 alvin 的全部兒子Son.

obj = session.query(Father).filter(Father.name=='alvin').first()

row = obj.son
for ret in row:
    print(ret.nid,ret.name,ret.father.name)

多對多,連表操做:

#!/usr/bin/env python
# -*-coding:utf-8 -*-

from sqlalchemy import create_engine,and_,or_,func,Table
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String,ForeignKey
from  sqlalchemy.orm import sessionmaker,relationship


engine = create_engine('mysql+pymysql://root@127.0.0.1:3307/day40?charset=utf8')

Base = declarative_base()

class Man_To_Woman(Base):

    __tablename__ = 'man_to_woman'
    nid = Column(Integer,primary_key=True)
    man_id = Column(Integer,ForeignKey('man.nid'))
    woman_id = Column(Integer,ForeignKey('woman.nid'))

class Man(Base):

    __tablename__ = 'man'
    nid = Column(Integer,primary_key=True)
    name = Column(String(20),nullable=False)
    woman = relationship("Woman", secondary=Man_To_Woman.__table__)

class Woman(Base):

    __tablename__ = 'woman'
    nid = Column(Integer,primary_key=True)
    name = Column(String(20),nullable=False)
    man = relationship("Man",secondary=Man_To_Woman.__table__)



Base.metadata.create_all(engine)

MySession = sessionmaker(engine)
session = MySession()
表結構

正,反向操做: 

1.alex的全部女人

2.鳳姐的全部男人

man1 = session.query(Man).filter(Man.name=='alex').first()
print(man1)
for ret in man1.woman:
    print(ret.nid,ret.name)

woman1 = session.query(Woman).filter(Woman.name=='fengjie').first()
print(woman1)
for ret in woman1.man:
    print(ret.nid,ret.name)

relatioinship 語句的簡寫:  ,我添加到Man表中

woman = relationship("Woman", secondary=Man_To_Woman.__table__,backref='man')

 

1   關於 session.add   session.query   session.commit的順序問題?

在同一個會話中, insert into table (xxxx)後,能夠接着 select * from xxx; 查詢到剛剛插入的數據;

只是不能在其餘會話,好比我另開一個客戶端去鏈接數據庫不能查詢到剛剛插入的數據。

這個數據已經到數據庫。值是數據庫吧這個數據給鎖了。只有插入數據的那個session能夠查看到,其餘的session不能查看到,能夠理解提交併解鎖吧。

相關文章
相關標籤/搜索