Python操作MySQL主要使用兩種方式:
- 原生模塊 pymsql
- ORM框架 sqlachemy
pymsql
下載安裝
pip3 install pymysql
使用操作
1、執行SQL
1 # -*- coding:utf-8 -*- 2 3 import pymysql 4 5 # 創建連接 6 conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='t1') 7 # 創建游標 8 cursor = conn.cursor() 9 10 # 執行SQL,並返回收影響行數 11 effect_row = cursor.execute("update hosts set host = '1.1.1.2'") 12 13 # 執行SQL,並返回受影響行數 14 #effect_row = cursor.execute("update hosts set host = '1.1.1.2' where nid > %s", (1,)) 15 16 # 執行SQL,並返回受影響行數 17 #effect_row = cursor.executemany("insert into hosts(host,color_id)values(%s,%s)", [("1.1.1.11",1),("1.1.1.11",2)]) 18 19 20 # 提交,不然無法保存新建或者修改的數據 21 conn.commit() 22 23 # 關閉游標 24 cursor.close() 25 # 關閉連接 26 conn.close()
2、獲取新創建數據自增ID
1 # -*- coding:utf-8 -*- 2 import pymysql 3 4 conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='t1') 5 cursor = conn.cursor() 6 cursor.executemany("insert into hosts(host,color_id)values(%s,%s)", [("1.1.1.11",1),("1.1.1.11",2)]) 7 conn.commit() 8 cursor.close() 9 conn.close() 10 11 # 獲取最新自增ID 12 new_id = cursor.lastrowid
3、獲取查詢數據
1 # -*- coding:utf-8 -*- 2 import pymysql 3 4 conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='t1') 5 cursor = conn.cursor() 6 cursor.execute("select * from hosts") 7 8 # 獲取第一行數據 9 row_1 = cursor.fetchone() 10 11 # 獲取前n行數據 12 # row_2 = cursor.fetchmany(3) 13 # 獲取所有數據 14 # row_3 = cursor.fetchall() 15 16 conn.commit() 17 cursor.close() 18 conn.close()
注:在fetch數據時按照順序進行,可以使用cursor.scroll(num,mode)來移動游標位置,如:
- cursor.scroll(1,mode='relative') # 相對當前位置移動
- cursor.scroll(2,mode='absolute') # 相對絕對位置移動
4、fetch數據類型
關於默認獲取的數據是元祖類型,如果想要或者字典類型的數據,即:
1 # -*- coding:utf-8 -*- 2 import pymysql 3 4 conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='t1') 5 6 # 游標設置為字典類型 7 cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) 8 r = cursor.execute("call p1()") 9 10 result = cursor.fetchone() 11 12 conn.commit() 13 cursor.close() 14 conn.close()
sqlachemy
sqlachemy是Python編程語言下的一款ORM框架,該框架建立在數據庫API之上,使用關系對象映射進行數據庫操作,簡言之便是:將對象轉換成SQL,然后使用數據API執行SQL並獲取執行結果。
安裝:
pip3 install sqlachemy
sqlachemy本身無法操作數據庫,其必須以來pymsql等第三方插件,Dialect用於和數據API進行交流,根據配置文件的不同調用不同的數據庫API,從而實現對數據庫的操作,如以pymsql為例:
mysql+pymysql://<username>:<password>@<host>/<dbname>[?<options>]
一、內部處理
使用 Engine/ConnectionPooling/Dialect 進行數據庫操作,Engine使用ConnectionPooling連接數據庫,然后再通過Dialect執行SQL語句。
1 # -*- coding:utf-8 -*- 2 from sqlalchemy import create_engine 3 4 5 engine = create_engine("mysql+pymysql://root:123@127.0.0.1:3306/t1", max_overflow=5) 6 7 # 執行SQL 8 # cur = engine.execute( 9 # "INSERT INTO hosts (host, color_id) VALUES ('1.1.1.22', 3)" 10 # ) 11 12 # 新插入行自增ID 13 # cur.lastrowid 14 15 # 執行SQL 16 # cur = engine.execute( 17 # "INSERT INTO hosts (host, color_id) VALUES(%s, %s)",[('1.1.1.22', 3),('1.1.1.221', 3),] 18 # ) 19 20 21 # 執行SQL 22 # cur = engine.execute( 23 # "INSERT INTO hosts (host, color_id) VALUES (%(host)s, %(color_id)s)", 24 # host='1.1.1.99', color_id=3 25 # ) 26 27 # 執行SQL 28 # cur = engine.execute('select * from hosts') 29 # 獲取第一行數據 30 # cur.fetchone() 31 # 獲取第n行數據 32 # cur.fetchmany(3) 33 # 獲取所有數據 34 # cur.fetchall()
二、ORM功能使用
使用 ORM/Schema Type/SQL Expression Language/Engine/ConnectionPooling/Dialect 所有組件對數據進行操作。根據類創建對象,對象轉換成SQL,執行SQL。
1、創建表
表結構 + 數據庫連接
1 # -*- coding:utf-8 -*- 2 from sqlalchemy.ext.declarative import declarative_base 3 from sqlalchemy import Column, Integer, String, ForeignKey, UniqueConstraint, Index 4 from sqlalchemy.orm import sessionmaker, relationship 5 from sqlalchemy import create_engine 6 7 engine = create_engine("mysql+pymysql://root:123@127.0.0.1:3306/t1", max_overflow=5) 8 9 Base = declarative_base() 10 11 # 創建單表 12 class Users(Base): 13 __tablename__ = 'users' 14 id = Column(Integer, primary_key=True) 15 name = Column(String(32)) 16 extra = Column(String(16)) 17 18 __table_args__ = ( 19 UniqueConstraint('id', 'name', name='uix_id_name'), 20 Index('ix_id_name', 'name', 'extra'), 21 ) 22 23 def __repr__(self): 24 return "%s-%s" %(self.id, self.name) 25 26 # 一對多 27 class Favor(Base): 28 __tablename__ = 'favor' 29 nid = Column(Integer, primary_key=True) 30 caption = Column(String(50), default='red', unique=True) 31 32 def __repr__(self): 33 return "%s-%s" %(self.nid, self.caption) 34 35 class Person(Base): 36 __tablename__ = 'person' 37 nid = Column(Integer, primary_key=True) 38 name = Column(String(32), index=True, nullable=True) 39 favor_id = Column(Integer, ForeignKey("favor.nid")) 40 # 與生成表結構無關,僅用於查詢方便 41 favor = relationship("Favor", backref='pers') 42 43 # 多對多 44 class ServerToGroup(Base): 45 __tablename__ = 'servertogroup' 46 nid = Column(Integer, primary_key=True, autoincrement=True) 47 server_id = Column(Integer, ForeignKey('server.id')) 48 group_id = Column(Integer, ForeignKey('group.id')) 49 group = relationship("Group", backref='s2g') 50 server = relationship("Server", backref='s2g') 51 52 class Group(Base): 53 __tablename__ = 'group' 54 id = Column(Integer, primary_key=True) 55 name = Column(String(64), unique=True, nullable=False) 56 port = Column(Integer, default=22) 57 # group = relationship('Group',secondary=ServerToGroup,backref='host_list') 58 59 60 class Server(Base): 61 __tablename__ = 'server' 62 63 id = Column(Integer, primary_key=True, autoincrement=True) 64 hostname = Column(String(64), unique=True, nullable=False) 65 66 67 68 69 def init_db(): 70 Base.metadata.create_all(engine) 71 72 73 def drop_db(): 74 Base.metadata.drop_all(engine) 75 76 77 Session = sessionmaker(bind=engine) 78 session = Session()
2、操作表
1 # -*- coding:utf-8 -*- 2 3 from sqlalchemy.ext.declarative import declarative_base 4 from sqlalchemy import Column, Integer, String 5 from sqlalchemy.orm import sessionmaker 6 from sqlalchemy import create_engine 7 8 engine = create_engine("mysql+mysqldb://root:123@127.0.0.1:3306/s11", max_overflow=5) 9 10 Base = declarative_base() 11 12 13 class User(Base): 14 __tablename__ = 'users' 15 id = Column(Integer, primary_key=True) 16 name = Column(String(50)) 17 18 # 尋找Base的所有子類,按照子類的結構在數據庫中生成對應的數據表信息 19 # Base.metadata.create_all(engine) 20 21 Session = sessionmaker(bind=engine) 22 session = Session() 23 24 25 # ########## 增 ########## 26 # u = User(id=2, name='sb') 27 # session.add(u) 28 # session.add_all([ 29 # User(id=3, name='sb'), 30 # User(id=4, name='sb') 31 # ]) 32 # session.commit() 33 34 # ########## 刪除 ########## 35 # session.query(User).filter(User.id > 2).delete() 36 # session.commit() 37 38 # ########## 修改 ########## 39 # session.query(User).filter(User.id > 2).update({'cluster_id' : 0}) 40 # session.commit() 41 # ########## 查 ########## 42 # ret = session.query(User).filter_by(name='sb').first() 43 44 # ret = session.query(User).filter_by(name='sb').all() 45 # print (ret) 46 47 # ret = session.query(User).filter(User.name.in_(['sb','bb'])).all() 48 # print (ret) 49 50 # ret = session.query(User.name.label('name_label')).all() 51 # print (ret,type(ret)) 52 53 # ret = session.query(User).order_by(User.id).all() 54 # print (ret) 55 56 # ret = session.query(User).order_by(User.id)[1:3] 57 # print (ret) 58 # session.commit()