日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > 数据库 >内容正文

数据库

python propresql mysql_python数据库操作mysql:pymysql、sqlalchemy常见用法详解

發布時間:2025/3/15 数据库 16 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python propresql mysql_python数据库操作mysql:pymysql、sqlalchemy常见用法详解 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

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

相關內容:

使用pymysql直接操作mysql

創建表

查看表

修改表

刪除表

插入數據

查看數據

修改數據

刪除數據

使用sqlmary操作mysql

創建表

查看表

修改表

刪除表

插入數據

查看數據

修改數據

刪除數據

首發時間:2018-02-24 23:59

修改:

2018-06-15,發現自己關于pymysql寫了對于數據的操作示例,但沒有寫表結構的示例,于是添加上

直接操作mysql--pymysql:

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

前提:

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

安裝模塊:pymysql:

pip3 install pymysql

或者在Pycharm中安裝

使用:

首先導入模塊:import pymysql

連接數據庫 :數據庫連接對象 = pymysql.connect("host="localhost",port=3306,user='root',passwd='123456',db='python_test') 【如果需要支持中文,則加上charset=”utf8”】

創建游標【游標用于執行sql語句和管理查詢到的結果】 :游標對象 = 數據庫連接對象.cursor()

執行sql語句 :游標對象.execute(SQL語句) ,返回值是受影響行數? 【execute可以執行所有的sql語句,不論是表相關的,還是數據相關的。】

由于默認開始事務,如果涉及修改、插入,則需要提交:連接對象.commit() ;以及撤銷修改、插入的回滾:連接對象.rollback()

executemany是同時執行多條sql語句【以多組參數的格式,executemany(self,query,args)】:

獲取結果:

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

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

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

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

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

關閉游標: 游標對象.close()

關閉數據庫連接:數據庫連接對象.close()

示例:

1.創建連接:

import pymysql

#創建連接

conn=pymysql.connect(host="localhost",port=3306,user="root",passwd="123456",db="python_test")

#創建游標

cursor=conn.cursor()

#..............操作過程

#關閉游標

cursor.close()

#關閉連接

conn.close()

2.執行創建表:

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()

3.執行查詢:

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()

4.執行插入、修改、刪除:

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, '男'))

---------------------------

5.設置支持中文【創建連接時添加charset=”utf8”】:

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()

添加前:

添加后:

使用sqlalchemy操作mysql:

介紹:

ORM 將數據庫中的表與面向對象語言中的類建立了一種對應關系,【ORM可以說是參照映射來處理數據的模型,比如說:需要創建一個表,可以定義一個類,而這個類存在與表相映射的屬性,那么可以通過操作這個類來創建一個表】

sqlmary是一個mysql的ORM

前提:

安裝模塊:pip3 install sqlalchemy

使用:

導入模塊:

導入連接數據庫模塊:from sqlalchemy import create_engine

如果需要創建新表,則需要導入表結構定義模塊:from sqlalchemy.ext.declarative import declarative_base

導入其他相關模塊,主要是映射的類,如字段映射為Column,如數據類型int映射為Integer,如索引映射為Index,需要什么導入什么:from sqlalchemy import Column,Integer,String

映射關系:

數據庫中

映射

模塊【如果可以從多個模塊處導入,用 | 分隔】【方式太多,可能有漏,但不影響導入】

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

連接數據庫:連接對象=create_engine('數據庫類型+數據庫驅動名稱://用戶名:口令@機器地址:端口號/數據庫名',編碼格式,echo)

sqlalchemy支持多種API操作模式,可以使用不同的模式來連接操作數據庫:'數據庫類型+數據庫驅動名稱://用戶名:口令@機器地址:端口號/數據庫名'

比如pymsql【py3常用】:mysql+pymysql://:@/[?

其他參數:

echo是否顯示ORM轉成實際sql語句的過程,echo=True為顯

encoding為連接時使用的字符集

操作:

基本操作:

創建新表

方法一: 使用declarative

1.導入模塊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)

方法二:使用Table

1.導入模塊: from sqlalchemy import Table

2.連接數據庫:engine=create_engine(….)

3.獲取meta類,metadata=MetaData(engine)

4.創建Table對象( 比如:t=Table("group" ,metadata,Column("id",Integer,primary_key=True),Column("group_name",String(32)))? )

5.創建表:metadata.create_all()

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)

查看表:

db_table=Base.metadata.tables#僅有當次運行中繼承了Base而創建的新表

db_tables=engine.table_names()#僅有表名

刪除表:Base.metadata.drop_all(engine)

修改表:

直接修改表所對應的類結構是無法修改成功的,

如果需要修改在程序中自定義的表的結構,那么需要手動修改,手動的方式有很多,比如直接engine.execute(sql語句)。。。。

插入 數據【這里僅針對使用declarative_base創建的表,對于不是程序中才創建的,可以自己使用declarative_base建一個類來映射之前的表,只要映射一致,就能插入數據】

1.連接數據庫: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.提交數據: s.commit()

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(表對應類)是相當于select對應表,后面可以跟first()、all()等來獲取結果,也可以加filter、filter_by等來篩選結果

獲取全部 : 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 ""%(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)

修改 數據:

修改數據的基礎是先查找到數據,查找:row=s.query(X).filter(X.xxx=xxx).first()

使用賦值語句修改 :row.xxx=xxxx

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 ""%(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()

刪除 數據:

刪除數據的基礎是先查找到數據,查找:row=s.query(X).filter(X.xxx=xxx)

使用delete刪除:row.delete()

# 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 ""%(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()

外鍵相關:

外鍵使用foregin_key創建

類中的relationship的作用:幫助ORM獲知他們的外鍵關系,以便ORM使用外鍵獲取相關數據

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.插入數據

4.查詢到一條數據:如row=s.query(User).filter(User.name=='lisi').first()

5.嘗試A表調用關系來獲取B(row.group_relation.group_name),B使用backref來獲取A的數據(row2.g_users)

下面的實例大概就是“一個開發人員對應一個開發組的關系”

#負責導入連接數據庫的對象

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 ""%(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 ""%(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的數據

一對多關系,外鍵關聯

以一個老師能做一個班的班主任此外還能做另一個班的副班主任為例【即一個老師能對應多個班級】

一對多關系的創建的核心是relationship中的foreign_keys

附:當你建表成功而插入數據失敗時,可以嘗試先刪除掉數據表,有時候因為外鍵依賴會導致插入失敗

#負責導入連接數據庫的對象

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 ""%(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 ""%(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)

多對多外鍵關聯

以選課中一門課能有多名學生,一個學生可以選多門課為示例:

其中relationship中的secondary的值是中間表,負責維持中間表與另外兩表的關系,創建多對多的核心是secondary

#負責導入連接數據庫的對象

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 ""%(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 ""%(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()

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

總結

以上是生活随笔為你收集整理的python propresql mysql_python数据库操作mysql:pymysql、sqlalchemy常见用法详解的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。