时间:2021-07-01 10:21:17 帮助过:14人阅读
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 |
mysql+pymysql://<username>:<password>@<host>/<dbname>[?<options>
encoding为连接时使用的字符集
基本操作:
from sqlalchemy.ext.declarative import declarative_base
2.根据需要的元素来导入模块
from sqlalchemy import Column
导入需要的数据类型【注:数据类型在sqlalchemy中也有指向,所以也可以from sqlalchemy import String,Integer,Char
】:
from sqlalchemy.types import *3.创建连接,
3.使用declarative_base来获得一个类对象,此处我定义该对象为Base
定义一个类,继承declarative_base生成的类对象Base
使用__tablename__来定义表名
使用 列名 = Column(数据类型,其他列属性…)等类似格式来定义字段
nullable=False
代表这一列不可以为空,index=True
表示在该列创建索创建表:
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)) 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)
Base.metadata.drop_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()
同样适用sessionmaker来查找,与插入相同,需要创建session_class对象(我定义为s)
使用s来查找:
获取全部
: s.query(表对应类).all() 【返回的是一个结果列表】
查找指定: s.query(表对应类).filter(表对应类.xxx==xxxx)【filter获取的是结果集,需要使用all(),first()等方法来获取结果】
查找指定: s.query(表对应类).filter_by(xxx=xxxx)
附:虽然返回值是一个结果集,但这个集合是一个类对象,如果想查看内容,需要在表对应的类中增加__repr__方法。
多个筛选条件使用“,”隔开
常见可用筛选条件【User是一个表对应的类】:
使用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 表]
连接查询使用:s.query(表对应类).join(表对应类.xxx==xxxx)
还有group_by,order_by等用法这里不做讲解[什么时候有空再补吧!]
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__="