python——连接mysql
Python操作MySQL
对于Python操作MySQL主要有两种方式:
- 原生模块 pymsql
- ORM框架 SQLAchemy
一、pymysql操作MySQL
1、执行sql语句
import pymysql conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='xxx', db='xingedb') # 创建连接 cursor = conn.cursor() # 创建游标,为了日后的回滚 effect_row = cursor.execute('select password from cmdb_userinfo where username = %s;',[name,]) # 执行SQL,并返回收影响行数 # 执行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() # 关闭连接
2、创建新数据并获取新创建数据的自增ID
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() new_id = cursor.lastrowid # 获取最新自增ID
3、获取查询数据
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() # 获取前n行数据 # row_2 = cursor.fetchmany(3) # 获取所有数据 # 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') # 相对绝对位置移动
4、fetch数据类型
关于默认获取的数据是元组(abc,)类型,如果想要或者字典类型的数据,即:
import pymysql conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='t1') cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) # 游标设置为字典类型 r = cursor.execute("call p1()") result = cursor.fetchone() conn.commit() cursor.close() conn.close()
二、SQLAchemy(ORM)操作MySQL
使用python创建一个表
1 from sqlalchemy import create_engine 2 from sqlalchemy.ext.declarative import declarative_base 3 from sqlalchemy import Column,Integer,String 4 from sqlalchemy.orm import sessionmaker 5 6 engine=create_engine('mysql+pymysql://root:123@localhost/xingedb',encoding='utf-8') 7 8 Base=declarative_base() #生成orm基类 9 10 class user(Base): 11 __tablename__='user' #创建的表名 12 id=Column(Integer,primary_key=True) 13 name=Column(String(32)) 14 password=Column(String(64)) 15 16 Base.metadata.create_all(engine) #创建表结构 17 Session_class=sessionmaker(bind=engine) #创建与数据库的会话session class ,注意,这里返回给session的是个class,不是实例 18 Session=Session_class() #生成实例 19 20 Session.commit() #保存操作
增、删、改、查
1 user_obj=User(name="x54256",password="123") #增 2 3 Session.add(user_obj) 4 5 Session.query(User).filter(User.id == 2).delete() #删 6 7 data= Session.query(User).filter_by(name="x54256").first() #查 8 print(data) 9 10 输出是一个obj: <__main__.User object at 0x000002CD45131D30> 11 12 在类下面加下面的代码,就会显示具体的数据了 13 14 def __repr__(self): 15 return "<User(name='%s', password='%s')>" % ( 16 self.name, self.password) 17 18 data= Session.query(User).filter_by(name="x54256").first() #改 19 data.name='alex' 20 data.password='abc' 21 22 Session.commit()
其他
1 #获取所有数据 2 print(Session.query(User.name,User.id).all() ) 3 4 #多条件查询 5 objs = Session.query(User).filter(User.id>0).filter(User.id<7).all() 6 7 #统计和分组 8 Session.query(User).filter(User.name.like("Ra%")).count()
外键关联
1 from sqlalchemy import create_engine 2 from sqlalchemy.ext.declarative import declarative_base 3 from sqlalchemy import Column,Integer,String,DATE,ForeignKey 4 from sqlalchemy.orm import sessionmaker,relationship 5 6 engine=create_engine('mysql+pymysql://root:123@localhost/xingedb',encoding='utf-8') 7 Base=declarative_base() 8 9 class Student(Base): 10 __tablename__='student' 11 id=Column(Integer,primary_key=True) 12 name=Column(String(32),nullable=False) 13 register_date=Column(DATE,nullable=False) 14 15 def __repr__(self): 16 return '<name:%s,register_date:%s >'%(self.name,self.register_date) 17 18 class StudyRecord(Base): 19 __tablename__='study_record' 20 id=Column(Integer, primary_key=True) 21 day=Column(Integer,nullable=False) 22 status=Column(String(32),nullable=False) 23 stu_id=Column(Integer,ForeignKey('student.id')) 24 student=relationship("Student",backref="my_study_record") 25 26 def __repr__(self): 27 return '<name:%s,day:%s,status:%s,stu_id:%s>'%(self.student.name,self.day,self.status,self.stu_id) 28 29 Base.metadata.create_all(engine) 30 Session_class=sessionmaker(bind=engine) 31 session=Session_class() 32 33 # s1=Student(name='alex',register_date="2014-05-21") 34 # s2=Student(name='jack',register_date="2014-04-21") 35 # s3=Student(name='rain',register_date="2014-03-21") 36 # s4=Student(name='eriv',register_date="2012-03-21") 37 # 38 # study_obj1=StudyRecord(day=1,status='No',stu_id=1) 39 # study_obj2=StudyRecord(day=2,status='Yes',stu_id=1) 40 # study_obj3=StudyRecord(day=2,status='No',stu_id=2) 41 # study_obj4=StudyRecord(day=3,status='Yes',stu_id=2) 42 # study_obj5=StudyRecord(day=1,status='Yes',stu_id=3) 43 # 44 # session.add_all([s1,s2,s3,s4,study_obj1,study_obj2,study_obj3,study_obj4,study_obj5]) 45 46 stu_obj=session.query(Student).filter(Student.name=='alex').first() 47 print(stu_obj.my_study_record) 48 49 50 session.commit()
1 stu_obj=session.query(Student).filter(Student.name=='alex').first() 2 print(stu_obj.my_study_record)
多外键关联
many_wk.py
1 from sqlalchemy import Integer, ForeignKey, String, Column 2 from sqlalchemy.ext.declarative import declarative_base 3 from sqlalchemy.orm import relationship 4 from sqlalchemy import create_engine 5 6 Base = declarative_base() 7 8 class Customer(Base): 9 __tablename__ = 'customer' 10 id = Column(Integer, primary_key=True) 11 name = Column(String(32)) 12 billing_address_id = Column(Integer, ForeignKey("address.id")) 13 shipping_address_id = Column(Integer, ForeignKey("address.id")) 14 15 billing_address = relationship("Address", foreign_keys=[billing_address_id]) #一定要这样写要不然,添加的时候回找不到 16 shipping_address = relationship("Address", foreign_keys=[shipping_address_id]) 17 18 class Address(Base): 19 __tablename__ = 'address' 20 id = Column(Integer, primary_key=True) 21 street = Column(String(32)) 22 city = Column(String(32)) 23 state = Column(String(32)) 24 def __repr__(self): 25 return '<%s,%s,%s>'%(self.state,self.city,self.street) 26 27 engine=create_engine('mysql+pymysql://root:123@localhost/xingedb',encoding='utf-8') 28 Base.metadata.create_all(engine) #创建表结构
多外键.py
1 from day_11 import many_wk 2 from sqlalchemy.orm import sessionmaker 3 4 Session_class=sessionmaker(bind=many_wk.engine) #创建与数据库的会话session class ,注意,这里返回给session的是个class,不是实例 5 Session=Session_class() #生成实例 6 7 # addr1=many_wk.Address(street='Tiantongyuan',city='Changping',state='BJ') 8 # addr2=many_wk.Address(street='Wudaokou',city='Haidian',state='BJ') 9 # addr3=many_wk.Address(street='Yanjiao',city='Langfang',state='HB') 10 # 11 # Session.add_all([addr1,addr2,addr3]) 12 # 13 # c1=many_wk.Customer(name='alex',billing_address=addr1,shipping_address=addr2) 14 # c2=many_wk.Customer(name='x54256',billing_address=addr3,shipping_address=addr3) 15 # Session.add_all([c1,c2]) 16 # 17 # Session.commit() #保存操作 18 19 data=Session.query(many_wk.Customer).filter(many_wk.Customer.name=='alex').first() 20 21 print(data.name,data.billing_address,data.shipping_address)
多对多关系
orm_m2m.py
1 from sqlalchemy import Table, Column, Integer,String,DATE, ForeignKey 2 from sqlalchemy.orm import relationship 3 from sqlalchemy.ext.declarative import declarative_base 4 from sqlalchemy import create_engine 5 6 Base = declarative_base() 7 book_m2m_author = Table('book_m2m_author', Base.metadata, 8 Column('book_id',Integer,ForeignKey('books.id')), 9 Column('author_id',Integer,ForeignKey('authors.id')), 10 ) 11 12 class Book(Base): 13 __tablename__ = 'books' 14 id = Column(Integer,primary_key=True) 15 name = Column(String(64)) 16 pub_date = Column(DATE) 17 authors = relationship('Author',secondary=book_m2m_author,backref='books') 18 19 def __repr__(self): 20 return self.name 21 22 class Author(Base): 23 __tablename__ = 'authors' 24 id = Column(Integer, primary_key=True) 25 name = Column(String(32)) 26 27 def __repr__(self): 28 return self.name 29 30 engine=create_engine('mysql+pymysql://root:710130520a@localhost/xingedb?charset=utf8') #这样写就可以输入中文啦 31 Base.metadata.create_all(engine) #创建表结构
多对多.py
1 from day_11 import orm_m2m 2 from sqlalchemy.orm import sessionmaker 3 4 5 6 Session_class = sessionmaker(bind=orm_m2m.engine) # 创建与数据库的会话session class ,注意,这里返回给session的是个class,不是实例 7 8 s = Session_class() # 生成session实例 9 10 # b1 = orm_m2m.Book(name="跟Alex学Python") 11 # b2 = orm_m2m.Book(name="跟Alex学把妹") 12 # b3 = orm_m2m.Book(name="跟Alex学装逼") 13 # b4 = orm_m2m.Book(name="跟Alex学开车") 14 # 15 # a1 = orm_m2m.Author(name="Alex") 16 # a2 = orm_m2m.Author(name="Jack") 17 # a3 = orm_m2m.Author(name="Rain") 18 # 19 # b1.authors = [a1, a2] #设定关系 20 # b2.authors = [a1, a2, a3] 21 # 22 # s.add_all([b1, b2, b3, b4, a1, a2, a3]) 23 24 25 print('--------通过书表查关联的作者---------') 26 book_obj = s.query(orm_m2m.Book).filter_by(name="跟Alex学Python").first() 27 print(book_obj.name, book_obj.authors) 28 29 print('--------通过作者表查关联的书---------') 30 author_obj = s.query(orm_m2m.Author).filter_by(name="Alex").first() 31 print(author_obj.name, author_obj.books) 32 33 34 s.commit()