本文实例讲述了python数据库操作mysql:pymysql、sqlalchemy常见用法。分享给大家供大家参考,具体如下:
直接操作mysql意思是利用python实现类似命令行模式下的mysql交互。
pip3 install pymysql或者在Pycharm中安装
获取一条结果:data = 游标对象.fetchone()
获取全部结果:data=游标对象.fetchall()
获取指定数量结果:data=游标对象.fetmany(x)
获取结果后,就会将对应的结果删掉,比如fetchone是获取一条,那么这一条就会从原来的结果中删除
游标对象.rowcount()可以获得执行sql语句后受影响的行数
import pymysql #创建连接 conn=pymysql.connect(host="localhost",port=3306,user="root",passwd="123456",db="python_test") #创建游标 cursor=conn.cursor() #..............操作过程 #关闭游标 cursor.close() #关闭连接 conn.close()
import pymysql conn=pymysql.connect(host="localhost",port=3306,user="root",password="123456",db="it",charset="utf8") cursor=conn.cursor() sql=""" create table user( id int PRIMARY KEY auto_increment, username VARCHAR(20), password VARCHAR(20), address VARCHAR(35) ) """ cursor.execute(sql) conn.commit() cursor.close() conn.close()
import pymysql #创建连接 conn=pymysql.connect(host="localhost",port=3306,user="root",passwd="123456",db="python_test",charset="utf8") #创建游标 cursor=conn.cursor() cursor.execute("select * from student;") print(cursor.fetchone())#获取一条 print(cursor.fetchmany(2))#获取两条 print(cursor.fetchall())#获取结果集合中的全部 #关闭游标 cursor.close() #关闭连接 conn.close()
import pymysql #创建连接 conn=pymysql.connect(host="localhost",port=3306,user="root",password="123456",db="python_test",charset="utf8") #创建游标 cursor=conn.cursor() print("-----------插入----------------") cursor.execute("insert into student values ('nazha',2000,'男');") cursor.execute("select * from student;") print(cursor.fetchall()) print("-----------插入----------------") #cursor.executemany(self,query,args) cursor.executemany("insert into student value(%s,%s,%s);",[('zhangsan',18,'男'),('lisi',18,'男')]) cursor.execute("select * from student;") print(cursor.fetchall()) print("-----------修改----------------") cursor.execute("update student set name = 'zhangsan1' where name = 'zhangsan';") cursor.execute("select * from student;") print(cursor.fetchall()) print("----------删除-----------------") cursor.execute("delete from student where name = 'lisi';") cursor.execute("select * from student;") print(cursor.fetchall()) print("---------------------------") #需要提交才能插入、成功修改、删除 conn.commit() #关闭游标 cursor.close() #关闭连接 conn.close()
结果:
(('lilei', 18, '男'), ('hanmeimei', 18, '女'), ('huluwa', 18, '男'), ('sunwukong', 18, '男'), ('baigujing', 3000, '女'), ('nazha', 2000, '男')) --------------------------- (('lilei', 18, '男'), ('hanmeimei', 18, '女'), ('huluwa', 18, '男'), ('sunwukong', 18, '男'), ('baigujing', 3000, '女'), ('nazha', 2000, '男'), ('zhangsan', 18, '男'), ('lisi', 18, '男')) --------------------------- (('lilei', 18, '男'), ('hanmeimei', 18, '女'), ('huluwa', 18, '男'), ('sunwukong', 18, '男'), ('baigujing', 3000, '女'), ('nazha', 2000, '男'), ('zhangsan1', 18, '男'), ('lisi', 18, '男')) --------------------------- (('lilei', 18, '男'), ('hanmeimei', 18, '女'), ('huluwa', 18, '男'), ('sunwukong', 18, '男'), ('baigujing', 3000, '女'), ('nazha', 2000, '男'), ('zhangsan1', 18, '男')) ---------------------------
import pymysql #创建连接 # conn=pymysql.connect(host="localhost",port=3306,user='root',passwd='123456',db='python_test') conn=pymysql.connect(host="localhost",port=3306,user='root',passwd='123456',db='python_test',charset="utf8") #创建游标 cursor = conn.cursor() effect_row= cursor.execute("select * from student;") print("执行成功,受影响行数:",effect_row) print(cursor.fetchall()) conn.commit() cursor.close() conn.close()
添加前:
添加后:
数据库中 | 映射 | 模块【如果可以从多个模块处导入,用 | 分隔】【方式太多,可能有漏,但不影响导入】 |
表 | Table | from sqlalchemy import Table |
int | Integer | from sqlalchemy.types import Integer |
索引 | Index | from sqlalchemy import Index |
字段、列 | Column | from sqlalchemy import Column |
varchar | VARCHAR、String | from sqlalchemy.types import String | from sqlalchemy import String |
外键 | ForeignKey |
from sqlalchemy import ForeignKey |
基本操作:
from sqlalchemy import create_engine#负责导入连接数据库的对象 from sqlalchemy.ext.declarative import declarative_base#负责导入创建表的api from sqlalchemy import Column #负责导入列 from sqlalchemy.types import *#负责导入列类型 #数据库连接 engine = create_engine("mysql+pymysql://root:123456@localhost/python_test",encoding ='utf-8',echo=True) #方式一: Base = declarative_base() class User(Base): __tablename__ = 'user'#表名 id = Column(Integer,primary_key=True) name = Column(String(32)) password = Column(String(64)) Base.metadata.create_all(engine)
from sqlalchemy import create_engine from sqlalchemy import Table from sqlalchemy import MetaData from sqlalchemy import Column from sqlalchemy.types import * from sqlalchemy.ext.declarative import declarative_base ####下面的注释部分可以与上面一句的未注释的替换 engine=create_engine("mysql+pymysql://root:123456@localhost/python_test",encoding ='utf-8',echo=True) metadata=MetaData(engine) ### # Base=declarative_base() t=Table( "group" ,metadata,#表名 # "group",Base.metadata, Column("id",Integer,primary_key=True), Column("group_name",String(32)) ) metadata.create_all() # Base.metadata.create_all(engine)
from sqlalchemy import create_engine#负责导入连接数据库的对象 from sqlalchemy.ext.declarative import declarative_base#负责导入创建表的api from sqlalchemy import Column #负责导入列 from sqlalchemy.types import *#负责导入列类型 #数据库连接 engine = create_engine("mysql+pymysql://root:123456@localhost/python_test",encoding ='utf-8',echo=True) Base = declarative_base() class User(Base): __tablename__ = 'user'#表名 id = Column(Integer,primary_key=True) name = Column(String(32)) password = Column(String(64)) group = Column(Integer) Base.metadata.create_all(engine) from sqlalchemy.orm import sessionmaker obj1=User(name='lisi',password='123456',group=1) Session=sessionmaker(bind=engine) s=Session() s.add(obj1)# users=[User(name='wangwu',password='123456',group=1), User(name='zhaoliu', password='123456', group=1), User(name='sunqi', password='123456', group=1) ] s.add_all(users)# s.commit()
使用filter,filter_by时: |
User.name=='lisi' |
User.name.like(“lisi%”)) |
User.name != 'lisi' |
User.name.any() |
or_(筛选条件) 【代表里面的多个筛选条件以or组合,需要导入:from sqlalchemy import or_】 |
and_(筛选条件) 【代表里面的多个筛选条件以and组合,需要导入:from sqlalchemy import and_】【默认是and】 |
in_([筛选条件]) 【使用比如User.name.in_(['xiaxia', 'lilei', 'lover'])】 |
使用all时,以下是放在query里面的: |
User.name [这相当于不使用where的select name from 表] |
from sqlalchemy import create_engine#负责导入连接数据库的对象 from sqlalchemy.ext.declarative import declarative_base#负责导入创建表的api from sqlalchemy import Column #负责导入列 from sqlalchemy.types import *#负责导入列类型 #数据库连接 engine = create_engine("mysql+pymysql://root:123456@localhost/python_test",encoding ='utf-8') Base = declarative_base() class User(Base): __tablename__ = 'user'#表名 id = Column(Integer,primary_key=True) name = Column(String(32)) password = Column(String(64)) group = Column(Integer) def __repr__(self): return "<id:%s name:%s group:%s>"%(self.id,self.name,self.group) Base.metadata.create_all(engine) from sqlalchemy.orm import sessionmaker obj1=User(name='lisi',password='123456',group=1) Session=sessionmaker(bind=engine) s=Session() a=s.query(User).all() a2=s.query(User).filter(User.name=='lisi').first() a3=s.query(User).filter_by(name='lisi').first() print(a) print(a2) print(a3)
from sqlalchemy import create_engine#负责导入连接数据库的对象 from sqlalchemy.ext.declarative import declarative_base#负责导入创建表的api from sqlalchemy import Column #负责导入列 from sqlalchemy.types import *#负责导入列类型 #数据库连接 engine = create_engine("mysql+pymysql://root:123456@localhost/python_test",encoding ='utf-8') Base = declarative_base() class User(Base): __tablename__ = 'user'#表名 id = Column(Integer,primary_key=True) name = Column(String(32)) password = Column(String(64)) group = Column(Integer) def __repr__(self): return "<id:%s name:%s group:%s>"%(self.id,self.name,self.group) Base.metadata.create_all(engine) from sqlalchemy.orm import sessionmaker obj1=User(name='lisi',password='123456',group=1) Session=sessionmaker(bind=engine) s=Session() row=s.query(User).filter(User.name=='lisi').first() row.name='lisi2' s.commit()
# coding: utf-8 from sqlalchemy import create_engine#负责导入连接数据库的对象 from sqlalchemy.ext.declarative import declarative_base#负责导入创建表的api from sqlalchemy import Column #负责导入列 from sqlalchemy.types import *#负责导入列类型 #数据库连接 engine = create_engine("mysql+pymysql://root:123456@localhost/python_test",encoding ='utf-8') Base = declarative_base() class User(Base): __tablename__ = 'user'#表名 id = Column(Integer,primary_key=True) name = Column(String(32)) password = Column(String(64)) group = Column(Integer) def __repr__(self): return "<id:%s name:%s group:%s>"%(self.id,self.name,self.group) Base.metadata.create_all(engine) from sqlalchemy.orm import sessionmaker obj1=User(name='lisi',password='123456',group=1) Session=sessionmaker(bind=engine) s=Session() a3=s.query(User).filter_by(name='lisi1') a3.delete() s.commit()
#负责导入连接数据库的对象 from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base#负责导入创建表的api from sqlalchemy import Column,ForeignKey #负责导入列 from sqlalchemy.types import *#负责导入列类型 from sqlalchemy.orm import relationship #数据库连接 engine = create_engine("mysql+pymysql://root:123456@localhost/python_test",encoding ='utf-8') Base = declarative_base() class Group(Base): __tablename__="group" id=Column(Integer,primary_key=True) group_name=Column(String(32),nullable=False) def __repr__(self): return "<id:%s group_name:%s>"%(self.id,self.group_name) class User(Base): __tablename__ = 'user'#表名 id = Column(Integer,primary_key=True) name = Column(String(32),nullable=False) password = Column(String(64),nullable=False) group = Column(Integer,ForeignKey("group.id"))#这里创建外键 group_relation=relationship('Group',backref="g_users")#为ORM指明关系,方便ORM处理,第一个是对应的类 def __repr__(self): return "<id:%s name:%s>"%(self.id,self.name) Base.metadata.create_all(engine) from sqlalchemy.orm import sessionmaker # group1=Group(group_name='python') # group2=Group(group_name='linux') # group3=Group(group_name='AI') # user1=User(name='lisi',password='123456',group=1) # user2=User(name='zhangsan',password='123456',group=2) # user3=User(name='wangwu',password='123456',group=3) # user4=User(name='lilei',password='123456',group=3) Session=sessionmaker(bind=engine) s=Session() # s.add_all([group1,group2,group3,user1,user2,user3,user4]) # s.commit() # row=s.query(User).filter(User.name=='lisi').first() row=s.query(User).first() print(row.group_relation.group_name)#这里User通过关系来获取Group的数据 row2=s.query(Group).first() print(row2) print(row2.g_users)#这里Group通过relationship的backref来获取User的数据
#负责导入连接数据库的对象 from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base#负责导入创建表的api from sqlalchemy import Column,ForeignKey #负责导入列 from sqlalchemy.types import *#负责导入列类型 from sqlalchemy.orm import relationship #数据库连接 engine = create_engine("mysql+pymysql://root:123456@localhost/python_test",encoding ='utf-8') Base = declarative_base() class Grade(Base): __tablename__="grade" id=Column(Integer,primary_key=True) grade_name=Column(String(32),nullable=False) def __repr__(self): return "<id:%s group_name:%s>"%(self.id,self.grade_name) class Teacher(Base): __tablename__ = 'teacher'#表名 id = Column(Integer,primary_key=True) name = Column(String(32),nullable=False) primary_grade = Column(Integer,ForeignKey("grade.id")) second_grade = Column(Integer,ForeignKey("grade.id")) primary_grade_relation=relationship('Grade',backref="first_teacher",foreign_keys=[primary_grade]) second_grade_relation=relationship('Grade',backref="second_teacher",foreign_keys=[second_grade]) def __repr__(self): return "<id:%s name:%s>"%(self.id,self.name) Base.metadata.create_all(engine) from sqlalchemy.orm import sessionmaker # grade1=Grade(grade_name='python') # grade2=Grade(grade_name='linux') # grade3=Grade(grade_name='AI') # grade4=Grade(grade_name='Java') # t1=Teacher(name='lisi',primary_grade=1,second_grade=2) # t2=Teacher(name='zhangsan',primary_grade=2,second_grade=1) # t3=Teacher(name='wangwu',primary_grade=4,second_grade=3) # t4=Teacher(name='lilei',primary_grade_relation=grade3,second_grade=4) #这里外键相关的比如primary_grade=x可以使用primary_grade_relation=对象来代替, # 会根据对象来转成对应id,不过问题是不知道grade3的准确id,因为可能创建顺序不一致 Session=sessionmaker(bind=engine) s=Session() # s.add_all([grade1,grade2,grade3,grade4]) # s.add_all([t1,t2,t3,t4]) # s.commit() row=s.query(Teacher).filter(Teacher.name=='lisi').first() print(row.name,row.primary_grade_relation.grade_name)#这里Teacher通过关系来获取Grade的数据 print(row.name,row.second_grade_relation.grade_name) row2=s.query(Grade).first() print(row2.grade_name,row2.first_teacher)#这里Grade通过relationship的backref来获取Teacher的数据 print(row2.grade_name,row2.second_teacher)
#负责导入连接数据库的对象 from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base#负责导入创建表的api from sqlalchemy import Column,ForeignKey #负责导入列 from sqlalchemy.types import *#负责导入列类型 from sqlalchemy.orm import relationship #数据库连接 engine = create_engine("mysql+pymysql://root:123456@localhost/python_test",encoding ='utf-8') Base = declarative_base() class SelectInfo(Base): __tablename__="selectClassInfo" id=Column(Integer,primary_key=True) sid=Column(Integer,ForeignKey("student.id")) cid=Column(Integer,ForeignKey("course.id")) """使用declarative_base和Table 创建表时,secondary的填写不一样 selectInfo2=Table( 'selectClassInfo',Base.metadata, Column('sid',Integer,ForeignKey('student.id')) Column('cid',Integer,ForeignKey('student.id')) ) """ class Student(Base): __tablename__="student" id=Column(Integer,primary_key=True) name=Column(String(32),nullable=False) def __repr__(self): return "<id:%s name:%s>"%(self.id,self.name) class Course(Base): __tablename__ = 'course' id = Column(Integer,primary_key=True) name = Column(String(32),nullable=False) student_relation=relationship('Student',secondary="selectClassInfo",backref="courses") # student_relation=relationship('Student',secondary=selectClassInfo2,backref="courses") # #如果使用Table来创建中间表,上面是这样填的 def __repr__(self): return "<id:%s name:%s>"%(self.id,self.name) Base.metadata.create_all(engine) from sqlalchemy.orm import sessionmaker # # s1=Student(name='lisi') # s2=Student(name='zhangsan') # s3=Student(name='wangwu') # s4=Student(name='lilei') # c1=Course(name='python',student_relation=[s1,s2]) # c2=Course(name='linux',student_relation=[s3]) # c3=Course(name='AI',student_relation=[s3,s4]) # c4=Course(name='Java') # c4.student_relation=[s1,s2,s3,s4]##在一边增加关系之后,在secondary中会加入两边的数据 # # # Session=sessionmaker(bind=engine) s=Session() # s.add_all([s1,s2,s3,s4,c1,c2,c3,c4]) # s.commit() row=s.query(Course).filter(Course.id=='4').first() print(row.name,row.student_relation)#这里Course通过关系来获取Student的数据 row2=s.query(Student).filter(Student.id=="3").first() print(row2.name,row2.courses)#这里Student通过relationship的backref来获取Course的数据
1.engine 可以直接运行sql语句,方式是engine.execute(),返回值是结果集,可以使用fetchall等方法来获取结果
2.其实创建表还有很多方法,可以使用各种对象来创建【比如在上面Table方式中也可以使用t来create(engine)】,但建议使用方式一
3.同样的,不单创建表有各种方法,查看表,删除表等也有多种操作方式,也是因为可以使用多种对象来操作
4.session也可以直接运行sql语句: session.execute()
附上sessionmake API官方文档:http://docs.sqlalchemy.org/en/latest/orm/session_api.html里面详尽而简单的讲解了用法
以及一个第三方辅助文档:https://www.pythonsheets.com/notes/python-sqlalchemy.html 里面有不少关于sqlalchemy的用法例子
更多关于Python相关内容感兴趣的读者可查看本站专题:《Python常见数据库操作技巧汇总》、《Python数学运算技巧总结》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》
希望本文所述对大家Python程序设计有所帮助。
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#nhooo.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。