电脑知识|欧美黑人一区二区三区|软件|欧美黑人一级爽快片淫片高清|系统|欧美黑人狂野猛交老妇|数据库|服务器|编程开发|网络运营|知识问答|技术教程文章 - 好吧啦网

您的位置:首頁技術文章
文章詳情頁

python數(shù)據(jù)庫操作mysql:pymysql、sqlalchemy常見用法詳解

瀏覽:3日期:2022-07-27 18:05:36

本文實例講述了python數(shù)據(jù)庫操作mysql:pymysql、sqlalchemy常見用法。分享給大家供大家參考,具體如下:

相關內(nèi)容: 使用pymysql直接操作mysql 創(chuàng)建表 查看表 修改表 刪除表 插入數(shù)據(jù) 查看數(shù)據(jù) 修改數(shù)據(jù) 刪除數(shù)據(jù) 使用sqlmary操作mysql 創(chuàng)建表 查看表 修改表 刪除表 插入數(shù)據(jù) 查看數(shù)據(jù) 修改數(shù)據(jù) 刪除數(shù)據(jù) 首發(fā)時間:2018-02-24 23:59 修改: 2018-06-15,發(fā)現(xiàn)自己關于pymysql寫了對于數(shù)據(jù)的操作示例,但沒有寫表結構的示例,于是添加上 直接操作mysql--pymysql:

直接操作mysql意思是利用python實現(xiàn)類似命令行模式下的mysql交互。

前提: 首先需要安裝python與mysql交互的庫【PyMySQL 是在 Python3 版本中用于連接 MySQL 服務器的一個庫】: 安裝模塊:pymysql:

pip3 install pymysql或者在Pycharm中安裝 使用: 首先導入模塊:import pymysql 連接數(shù)據(jù)庫 :數(shù)據(jù)庫連接對象 = pymysql.connect('host='localhost',port=3306,user=’root’,passwd=’123456’,db=’python_test’) 【如果需要支持中文,則加上charset=”utf8”】python數(shù)據(jù)庫操作mysql:pymysql、sqlalchemy常見用法詳解 創(chuàng)建游標【游標用于執(zhí)行sql語句和管理查詢到的結果】 :游標對象 = 數(shù)據(jù)庫連接對象.cursor() 執(zhí)行sql語句 :游標對象.execute(SQL語句) ,返回值是受影響行數(shù) 【execute可以執(zhí)行所有的sql語句,不論是表相關的,還是數(shù)據(jù)相關的。】 由于默認開始事務,如果涉及修改、插入,則需要提交:連接對象.commit() ;以及撤銷修改、插入的回滾:連接對象.rollback() executemany是同時執(zhí)行多條sql語句【以多組參數(shù)的格式,executemany(self,query,args)】: python數(shù)據(jù)庫操作mysql:pymysql、sqlalchemy常見用法詳解 獲取結果:

獲取一條結果:data = 游標對象.fetchone()

獲取全部結果:data=游標對象.fetchall()

獲取指定數(shù)量結果:data=游標對象.fetmany(x)

獲取結果后,就會將對應的結果刪掉,比如fetchone是獲取一條,那么這一條就會從原來的結果中刪除

游標對象.rowcount()可以獲得執(zhí)行sql語句后受影響的行數(shù)

python數(shù)據(jù)庫操作mysql:pymysql、sqlalchemy常見用法詳解 關閉游標: 游標對象.close() 關閉數(shù)據(jù)庫連接:數(shù)據(jù)庫連接對象.close()示例:1.創(chuàng)建連接:

import pymysql#創(chuàng)建連接conn=pymysql.connect(host='localhost',port=3306,user='root',passwd='123456',db='python_test')#創(chuàng)建游標cursor=conn.cursor()#..............操作過程#關閉游標cursor.close()#關閉連接conn.close()2.執(zhí)行創(chuàng)建表:

import pymysqlconn=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()3.執(zhí)行查詢:

import pymysql#創(chuàng)建連接conn=pymysql.connect(host='localhost',port=3306,user='root',passwd='123456',db='python_test',charset='utf8')#創(chuàng)建游標cursor=conn.cursor()cursor.execute('select * from student;')print(cursor.fetchone())#獲取一條print(cursor.fetchmany(2))#獲取兩條print(cursor.fetchall())#獲取結果集合中的全部#關閉游標cursor.close()#關閉連接conn.close()4.執(zhí)行插入、修改、刪除:

import pymysql#創(chuàng)建連接conn=pymysql.connect(host='localhost',port=3306,user='root',password='123456',db='python_test',charset='utf8')#創(chuàng)建游標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, ’男’))---------------------------5.設置支持中文【創(chuàng)建連接時添加charset=”utf8”】:

import pymysql#創(chuàng)建連接# 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')#創(chuàng)建游標cursor = conn.cursor()effect_row= cursor.execute('select * from student;')print('執(zhí)行成功,受影響行數(shù):',effect_row)print(cursor.fetchall())conn.commit()cursor.close()conn.close()

添加前:

python數(shù)據(jù)庫操作mysql:pymysql、sqlalchemy常見用法詳解

添加后:

python數(shù)據(jù)庫操作mysql:pymysql、sqlalchemy常見用法詳解

使用sqlalchemy操作mysql:介紹: ORM 將數(shù)據(jù)庫中的表與面向?qū)ο笳Z言中的類建立了一種對應關系,【ORM可以說是參照映射來處理數(shù)據(jù)的模型,比如說:需要創(chuàng)建一個表,可以定義一個類,而這個類存在與表相映射的屬性,那么可以通過操作這個類來創(chuàng)建一個表】 sqlmary是一個mysql的ORM前提: 安裝模塊:pip3 install sqlalchemy 使用: 導入模塊: 導入連接數(shù)據(jù)庫模塊:from sqlalchemy import create_engine 如果需要創(chuàng)建新表,則需要導入表結構定義模塊:from sqlalchemy.ext.declarative import declarative_base 導入其他相關模塊,主要是映射的類,如字段映射為Column,如數(shù)據(jù)類型int映射為Integer,如索引映射為Index,需要什么導入什么:from sqlalchemy import Column,Integer,String 映射關系: 數(shù)據(jù)庫中 映射 模塊【如果可以從多個模塊處導入,用 | 分隔】【方式太多,可能有漏,但不影響導入】 表 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 連接數(shù)據(jù)庫:連接對象=create_engine(’數(shù)據(jù)庫類型+數(shù)據(jù)庫驅(qū)動名稱://用戶名:口令@機器地址:端口號/數(shù)據(jù)庫名’,編碼格式,echo) sqlalchemy支持多種API操作模式,可以使用不同的模式來連接操作數(shù)據(jù)庫:’數(shù)據(jù)庫類型+數(shù)據(jù)庫驅(qū)動名稱://用戶名:口令@機器地址:端口號/數(shù)據(jù)庫名’ 比如pymsql【py3常用】:mysql+pymysql://<username>:<password>@<host>/<dbname>[?<options> 其他參數(shù): echo是否顯示ORM轉(zhuǎn)成實際sql語句的過程,echo=True為顯 encoding為連接時使用的字符集 操作:

基本操作:

創(chuàng)建新表 方法一: 使用declarative 1.導入模塊from sqlalchemy.ext.declarative import declarative_base2.根據(jù)需要的元素來導入模塊from sqlalchemy import Column 導入需要的數(shù)據(jù)類型【注:數(shù)據(jù)類型在sqlalchemy中也有指向,所以也可以from sqlalchemy import String,Integer,Char】:from sqlalchemy.types import *3.創(chuàng)建連接,3.使用declarative_base來獲得一個類對象,此處我定義該對象為Base定義一個類,繼承declarative_base生成的類對象Base 使用__tablename__來定義表名 使用 列名 = Column(數(shù)據(jù)類型,其他列屬性…)等類似格式來定義字段 nullable=False 代表這一列不可以為空,index=True 表示在該列創(chuàng)建索 創(chuàng)建表:Base.metadata.create_all(engine)

from sqlalchemy import create_engine#負責導入連接數(shù)據(jù)庫的對象from sqlalchemy.ext.declarative import declarative_base#負責導入創(chuàng)建表的apifrom sqlalchemy import Column #負責導入列from sqlalchemy.types import *#負責導入列類型#數(shù)據(jù)庫連接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) 方法二:使用Table 1.導入模塊: from sqlalchemy import Table2.連接數(shù)據(jù)庫:engine=create_engine(….)3.獲取meta類,metadata=MetaData(engine)4.創(chuàng)建Table對象( 比如:t=Table('group' ,metadata,Column('id',Integer,primary_key=True),Column('group_name',String(32))) )5.創(chuàng)建表:metadata.create_all()

from sqlalchemy import create_enginefrom sqlalchemy import Tablefrom sqlalchemy import MetaDatafrom sqlalchemy import Columnfrom 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) 查看表: db_table=Base.metadata.tables#僅有當次運行中繼承了Base而創(chuàng)建的新表 db_tables=engine.table_names()#僅有表名 刪除表:Base.metadata.drop_all(engine) 修改表: 直接修改表所對應的類結構是無法修改成功的, 如果需要修改在程序中自定義的表的結構,那么需要手動修改,手動的方式有很多,比如直接engine.execute(sql語句)。。。。插入 數(shù)據(jù)【這里僅針對使用declarative_base創(chuàng)建的表,對于不是程序中才創(chuàng)建的,可以自己使用declarative_base建一個類來映射之前的表,只要映射一致,就能插入數(shù)據(jù)】 1.連接數(shù)據(jù)庫:engine=create_engine(….) 1.導入模塊:from sqlalchemy.orm import sessionmaker 2.獲取session_class類:Session_class=sessionmaker(bind=engine) 3.獲取session對象:s=Session_class() 4.使用s來添加: s.add()s.add_all() 5.提交數(shù)據(jù): s.commit()

from sqlalchemy import create_engine#負責導入連接數(shù)據(jù)庫的對象from sqlalchemy.ext.declarative import declarative_base#負責導入創(chuàng)建表的apifrom sqlalchemy import Column #負責導入列from sqlalchemy.types import *#負責導入列類型#數(shù)據(jù)庫連接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 sessionmakerobj1=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() 查找 數(shù)據(jù) 同樣適用sessionmaker來查找,與插入相同,需要創(chuàng)建session_class對象(我定義為s) 使用s來查找: s.query(表對應類)是相當于select對應表,后面可以跟first()、all()等來獲取結果,也可以加filter、filter_by等來篩選結果獲取全部 : s.query(表對應類).all() 【返回的是一個結果列表】查找指定: s.query(表對應類).filter(表對應類.xxx==xxxx)【filter獲取的是結果集,需要使用all(),first()等方法來獲取結果】查找指定: s.query(表對應類).filter_by(xxx=xxxx)附:雖然返回值是一個結果集,但這個集合是一個類對象,如果想查看內(nèi)容,需要在表對應的類中增加__repr__方法。多個篩選條件使用“,”隔開常見可用篩選條件【User是一個表對應的類】: 使用filter,filter_by時:

User.name==’lisi’

User.name.like(“l(fā)isi%”))

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#負責導入連接數(shù)據(jù)庫的對象from sqlalchemy.ext.declarative import declarative_base#負責導入創(chuàng)建表的apifrom sqlalchemy import Column #負責導入列from sqlalchemy.types import *#負責導入列類型#數(shù)據(jù)庫連接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 sessionmakerobj1=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) 修改 數(shù)據(jù): 修改數(shù)據(jù)的基礎是先查找到數(shù)據(jù),查找:row=s.query(X).filter(X.xxx=xxx).first() 使用賦值語句修改 :row.xxx=xxxx

from sqlalchemy import create_engine#負責導入連接數(shù)據(jù)庫的對象from sqlalchemy.ext.declarative import declarative_base#負責導入創(chuàng)建表的apifrom sqlalchemy import Column #負責導入列from sqlalchemy.types import *#負責導入列類型#數(shù)據(jù)庫連接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 sessionmakerobj1=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() 刪除 數(shù)據(jù): 刪除數(shù)據(jù)的基礎是先查找到數(shù)據(jù),查找:row=s.query(X).filter(X.xxx=xxx) 使用delete刪除:row.delete()

# coding: utf-8from sqlalchemy import create_engine#負責導入連接數(shù)據(jù)庫的對象from sqlalchemy.ext.declarative import declarative_base#負責導入創(chuàng)建表的apifrom sqlalchemy import Column #負責導入列from sqlalchemy.types import *#負責導入列類型#數(shù)據(jù)庫連接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 sessionmakerobj1=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()外鍵相關: 外鍵使用foregin_key創(chuàng)建 類中的relationship的作用:幫助ORM獲知他們的外鍵關系,以便ORM使用外鍵獲取相關數(shù)據(jù) relationship中的backref的用途:relationship使得可以在一個表中定義的relationshop能被兩個表使用,另一個表使用backref來獲取相關信息 relationship中的foreign_keys的用途:當有多個relationship時,為了避免ORM混淆多個relationship,特別的標注哪個外鍵是哪個relationship relationship中的secondary的用途:在多對多的關系中,填入的值是中間表,維持兩邊表關系。 一對一的外鍵關系: 1.導入模塊:from sqlalchemy import Foreign_key 2.建立外鍵(如:group = Column(Integer,ForeignKey('group.id')),建立關系(如:group_relation=relationship(’Group’,backref='g_users') 3.插入數(shù)據(jù) 4.查詢到一條數(shù)據(jù):如row=s.query(User).filter(User.name==’lisi’).first() 5.嘗試A表調(diào)用關系來獲取B(row.group_relation.group_name),B使用backref來獲取A的數(shù)據(jù)(row2.g_users) 下面的實例大概就是“一個開發(fā)人員對應一個開發(fā)組的關系”

#負責導入連接數(shù)據(jù)庫的對象from sqlalchemy import create_enginefrom sqlalchemy.ext.declarative import declarative_base#負責導入創(chuàng)建表的apifrom sqlalchemy import Column,ForeignKey #負責導入列from sqlalchemy.types import *#負責導入列類型from sqlalchemy.orm import relationship#數(shù)據(jù)庫連接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'))#這里創(chuàng)建外鍵 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的數(shù)據(jù)row2=s.query(Group).first()print(row2)print(row2.g_users)#這里Group通過relationship的backref來獲取User的數(shù)據(jù)一對多關系,外鍵關聯(lián) 以一個老師能做一個班的班主任此外還能做另一個班的副班主任為例【即一個老師能對應多個班級】 一對多關系的創(chuàng)建的核心是relationship中的foreign_keys 附:當你建表成功而插入數(shù)據(jù)失敗時,可以嘗試先刪除掉數(shù)據(jù)表,有時候因為外鍵依賴會導致插入失敗

#負責導入連接數(shù)據(jù)庫的對象from sqlalchemy import create_enginefrom sqlalchemy.ext.declarative import declarative_base#負責導入創(chuàng)建表的apifrom sqlalchemy import Column,ForeignKey #負責導入列from sqlalchemy.types import *#負責導入列類型from sqlalchemy.orm import relationship#數(shù)據(jù)庫連接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=對象來代替,# 會根據(jù)對象來轉(zhuǎn)成對應id,不過問題是不知道grade3的準確id,因為可能創(chuàng)建順序不一致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的數(shù)據(jù)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的數(shù)據(jù)print(row2.grade_name,row2.second_teacher) 多對多外鍵關聯(lián) 以選課中一門課能有多名學生,一個學生可以選多門課為示例: 其中relationship中的secondary的值是中間表,負責維持中間表與另外兩表的關系,創(chuàng)建多對多的核心是secondary

#負責導入連接數(shù)據(jù)庫的對象from sqlalchemy import create_enginefrom sqlalchemy.ext.declarative import declarative_base#負責導入創(chuàng)建表的apifrom sqlalchemy import Column,ForeignKey #負責導入列from sqlalchemy.types import *#負責導入列類型from sqlalchemy.orm import relationship#數(shù)據(jù)庫連接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 創(chuàng)建表時,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來創(chuàng)建中間表,上面是這樣填的 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中會加入兩邊的數(shù)據(jù)###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的數(shù)據(jù)row2=s.query(Student).filter(Student.id=='3').first()print(row2.name,row2.courses)#這里Student通過relationship的backref來獲取Course的數(shù)據(jù)補充說明:

1.engine 可以直接運行sql語句,方式是engine.execute(),返回值是結果集,可以使用fetchall等方法來獲取結果

2.其實創(chuàng)建表還有很多方法,可以使用各種對象來創(chuàng)建【比如在上面Table方式中也可以使用t來create(engine)】,但建議使用方式一

3.同樣的,不單創(chuàng)建表有各種方法,查看表,刪除表等也有多種操作方式,也是因為可以使用多種對象來操作

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相關內(nèi)容感興趣的讀者可查看本站專題:《Python常見數(shù)據(jù)庫操作技巧匯總》、《Python數(shù)學運算技巧總結》、《Python數(shù)據(jù)結構與算法教程》、《Python函數(shù)使用技巧總結》、《Python字符串操作技巧匯總》、《Python入門與進階經(jīng)典教程》及《Python文件與目錄操作技巧匯總》

希望本文所述對大家Python程序設計有所幫助。

標簽: Python 編程
相關文章:
主站蜘蛛池模板: 消防泵-XBD单级卧式/立式消防泵-上海塑泉泵阀(集团)有限公司 | 盘式曝气器-微孔曝气器-管式曝气器-曝气盘-斜管填料 | 郑州市前程水处理有限公司 | 淘气堡_室内儿童乐园_户外无动力儿童游乐设备-高乐迪(北京) | PTFE接头|聚四氟乙烯螺丝|阀门|薄膜|消解罐|聚四氟乙烯球-嘉兴市方圆氟塑制品有限公司 | 小程序开发公司_APP开发多少钱_软件开发定制_微信小程序制作_客户销售管理软件-济南小溪畅流网络科技有限公司 | 众能联合-提供高空车_升降机_吊车_挖机等一站工程设备租赁 | 品牌策划-品牌设计-济南之式传媒广告有限公司官网-提供品牌整合丨影视创意丨公关活动丨数字营销丨自媒体运营丨数字营销 | 托盘租赁_塑料托盘租赁_托盘出租_栈板出租_青岛托盘租赁-优胜必达 | 日本SMC气缸接头-速度控制阀-日本三菱伺服电机-苏州禾力自动化科技有限公司 | 钢丝绳探伤仪-钢丝绳检测仪-钢丝绳探伤设备-洛阳泰斯特探伤技术有限公司 | 欧美日韩国产一区二区三区不_久久久久国产精品无码不卡_亚洲欧洲美洲无码精品AV_精品一区美女视频_日韩黄色性爱一级视频_日本五十路人妻斩_国产99视频免费精品是看4_亚洲中文字幕无码一二三四区_国产小萍萍挤奶喷奶水_亚洲另类精品无码在线一区 | 水平垂直燃烧试验仪-灼热丝试验仪-漏电起痕试验仪-针焰试验仪-塑料材料燃烧检测设备-IP防水试验机 | 贵州成人高考网_贵州成考网| 阳光1号桔柚_无核沃柑_柑橘新品种枝条苗木批发 - 苧金网 | 北京软件开发_软件开发公司_北京软件公司-北京宜天信达软件开发公司 | 定硫仪,量热仪,工业分析仪,马弗炉,煤炭化验设备厂家,煤质化验仪器,焦炭化验设备鹤壁大德煤质工业分析仪,氟氯测定仪 | 柔软云母板-硬质-水位计云母片组件-首页-武汉长丰云母绝缘材料有限公司 | 打包钢带,铁皮打包带,烤蓝打包带-高密市金和金属制品厂 | 压滤机-洗沙泥浆处理-压泥机-山东创新华一环境工程有限公司 | 交联度测试仪-湿漏电流测试仪-双85恒温恒湿试验箱-常州市科迈实验仪器有限公司 | 吸音板,隔音板,吸音材料,吸音板价格,声学材料 - 佛山诺声吸音板厂家 | 除尘布袋_液体过滤袋_针刺毡滤料-杭州辉龙过滤技术有限公司 | 耐火浇注料价格-高强高铝-刚玉碳化硅耐磨浇注料厂家【直销】 | 月嫂_保姆_育婴_催乳_母婴护理_产后康复_养老护理-吉祥到家家政 硫酸亚铁-聚合硫酸铁-除氟除磷剂-复合碳源-污水处理药剂厂家—长隆科技 | 浙江上沪阀门有限公司 | 膏方加工_丸剂贴牌_膏滋代加工_湖北康瑞生物科技有限公司 | 南京租车,南京汽车租赁,南京包车,南京会议租车-南京七熹租车 | 除尘器布袋骨架,除尘器滤袋,除尘器骨架,电磁脉冲阀膜片,卸灰阀,螺旋输送机-泊头市天润环保机械设备有限公司 | 高空重型升降平台_高空液压举升平台_高空作业平台_移动式升降机-河南华鹰机械设备有限公司 | 耐火浇注料-喷涂料-浇注料生产厂家_郑州市元领耐火材料有限公司 耐力板-PC阳光板-PC板-PC耐力板 - 嘉兴赢创实业有限公司 | 英国公司注册-新加坡公司注册-香港公司开户-离岸公司账户-杭州商标注册-杭州优创企业 | 挤奶设备过滤纸,牛奶过滤纸,挤奶机过滤袋-济南蓝贝尔工贸有限公司 | 欧景装饰设计工程有限公司-无锡欧景装饰官网 | 视频直播 -摄影摄像-视频拍摄-直播分发 | 陕西自考报名_陕西自学考试网 | 【甲方装饰】合肥工装公司-合肥装修设计公司,专业从事安徽办公室、店面、售楼部、餐饮店、厂房装修设计服务 | 艺术漆十大品牌_艺术涂料加盟代理_蒙太奇艺术涂料厂家品牌|艺术漆|微水泥|硅藻泥|乳胶漆 | 高精度电阻回路测试仪-回路直流电阻测试仪-武汉特高压电力科技有限公司 | 山东活动策划|济南活动公司|济南公关活动策划-济南锐嘉广告有限公司 | 丹佛斯变频器-丹佛斯压力开关-变送器-广州市风华机电设备有限公司 | 挤奶设备过滤纸,牛奶过滤纸,挤奶机过滤袋-济南蓝贝尔工贸有限公司 |