第柒1篇

本篇对于Python操作MySQL主要选用二种办法:

1、原生模块pymsql。

2、ORM框架SQLAchemy。

pymsql

pymsql是Python中操作MySQL的模块,其采用情势和MySQLdb大概等同。

windows下载安装

  1. pip3 install pymysql

利用操作

执行SQL

  1. __author__ = ‘Golden’

  2. #!/usr/bin/env python3

  3. # -*- coding:utf-8 -*-

  4. import pymysql

  5.  

  6. # 创立连接

  7. conn =
    pymysql.connect(host=’192.168.31.134′,port=3306,user=’root’,passwd=’123456′,db=’information_schema’)

  1. # 创造游标

  2. cursor = conn.cursor()

  3. # 施行SQL,并回到受影响行数

  4. effect_row = cursor.execute(“select * from tables”)

  5. print(effect_row)

  6. # 收取一条数据

  7. print(cursor.fetchone())

  8. # 取出前n条数据

  9. print(“*********************************************************”)

  1. print(cursor.fetchmany(5))

  2. # 抽出装有数据

  3. print(“*********************************************************”)

  1. print(cursor.fetchall())

  2. # 提交,否则无法保存新建或涂改的多少

  1. conn.commit()

  2. # 关闭游标

  3. cursor.close()

  4. # 关闭连接

  5. conn.close()

大概报错:pymysql.err.InternalError: (1130, “Host ‘192.168.3一.一’ is not
allowed to connect to this MySQL server”)

唯恐是因为您的账号不容许从远程登入,只辛亏localhost登入。只必要在localhost的那台Computer登六mysql,更动对应数据Curry的”user”表里的”host”项,把”localhost”改为”%”。

解决办法:

1、改表法

  1. [root@lnmp ~]# mysql -uroot -p123456
  1. mysql> use test;

  2. Database changed

  3. mysql> update user set host = ‘%’ where user = ‘root’;

  1. mysql> select host,user from user;
  1. mysql> flush rivileges;

2、授权法

同意用户user使用密码password从此外主机连接到mysql服务器。

  1. mysql> grant all privileges on *.*
    to ‘user’@’%’ identified by ‘password’ with grant option;

  2. mysql> flush privileges;

允许用户user从ip1玖二.168.1.12二的主机连接到mysql服务器,并行使password作为密码。

  1. mysql> grant all privileges on *.*
    to ‘user’@’192.168.1.122’ identified by ‘password’ with grant
    option;

  2. mysql> flush privileges;

允许用户user从ip1玖二.16八.1.12二的主机连接到mysql服务器的test_db数据库,并选拔password作为密码。

  1. mysql> grant all privileges on
    test_db.* to ‘user’@’192.168.1.122’ identified by ‘password’ with
    grant option;

  2. mysql> flush privileges;

布置数据

  1. # 插入数据

  2. effect_row = cursor.executemany(“inster into
    table_name(field_name1,field_name2)
    values(%s,%s)”,[(“value_1″,”value_2”),(“value_3″,”value_4”)])

SQLAlchemy ORM

ORM介绍

对象关系映射(Object Relational
Mapping,简称O中华VM),是1种程序技巧,用于得以落成面向对象编制程序语言里差别体系系统的数目里面包车型地铁调换。从功用上说,它其实是创办了三个可在编制程序语言里应用的——”虚拟对象数据库”。

面向对象是从软件工程大旨规则(如耦合、聚合、封装)的功底上发展兴起的,而关周全据库则是从数学理论发展而来的,两套理论存在分明的区分。为了消除那些不相配的场景,对象关系映射技巧现身。

目的关系映射(Object Relational
Mapping)提供了概念性的、易于明白的模型化数据的方法。O福特ExplorerM方法论基于八个着力规范。简单,以最宗旨的样式建立模型数据。传达性,数据库结构被任哪个人都能领略的语言文书档案化。正确性,基于数据模型创立准确标准的布局。规范地,建模者通过搜集来自那多少个熟谙应用程序但不懂行数据建模者开辟音讯模型。建立模型者必须能够用非本领集团专家能够知道的术语在概念等级次序上与数据结构举行报纸发表。建立模型者也非得能以简练的单元分析消息,对样本数量开展管理。OPRADOM专门被设计为改革那种关系。

图片 1

ORM的优点

1、隐藏了数量访问细节,”封闭”的通用数据库交互,OEscortM的中央。使得通用数据库的并行变得轻松易行,并且完全不用思索SQL语句。

2、OLANDM使协会固化数据结构变得轻松易行。

ORM的缺点

壹、自动化意味着映射和涉嫌管理,代价是捐躯品质。以后各个O纳瓦拉M框架都在品尝选取各类措施(如LazyLoad、Cache)来缓慢解决质量的熏陶,效果相比鲜明。

二、面向对象的询问语言(OQL)作为壹种数据库与对象时期的连结,即使隐藏了数额层面包车型地铁事体抽象,但并不可能完全的屏蔽掉数据库层的陈设性,并且确实将扩展学习成本。

叁、对于复杂查询,O帕杰罗M还是不大概。即便能够达成,不过不值得。视图能够消除大多数calculated
column、case、group、having、order by、exists,可是查询条件a and b and
not c and (d or e)不可能很好消除。

常用的ORM框架

1、Hibernate全自动必要hql语句。

二、iBatis半自动自身写sql语句,可操作性强,小巧。

三、EclipseLink二个可扩充的帮忙JPA的O奥迪Q3M框架,提供强劲的缓存作用,缓存帮忙集群。

4、Apache OJB等等。

五、在Python中最有名的O大切诺基M框架是SQLAlchemy。

SQLAlchemy安装

SQLAlchemy的见地是,SQL数据库的量级和总体性首要于对象集结,而目标集结的抽象又主要与表和行。

图片 2

Dialect用于和数据API举行沟通,依据安排文件的分歧调用差异的数据库API,从而达成对数据库的操作。

  1. MySQL-Python

  2.     mysql+mysqldb://<user>:<password>@<host>[:<port>]/<dbname>

  1.  

  2. pymysql

  3.     mysql+pymysql://<username>:<password>@<host>/<dbname>[?<options>]

  1.  

  2. MySQL-Connector

  3.     mysql+mysqlconnector://<user>:<password>@<host>[:<port>]/<dbname>

  1.  

  2. cx_Oracle

  3.     oracle+cx_oracle://user:pass@host:port/dbname[?key=value&key=value…]

  1.  

  2. 更加多详见:http://docs.sqlalchemy.org/en/latest/dialects/index.html

安装sqlalchemy

  1. pip3 install sqlalchemy

SQLAlchemy基本采取

创立二个表。

SQL实现:

  1. CREATE TABLE USER(

  2.    ID INTEGER NOT NULL AUTO_INCREMENT,

  1.    NAME VARCHAR(32),

  2.    PASSWORD VARCHAR(64),

  3.    PRIMARY KET (ID)

  4. )

ORM实现:

  1. __author__ = ‘Golden’

  2. #!/usr/bin/env python3

  3. # -*- coding:utf-8 -*-

  4.  

  5. import sqlalchemy

  6.  

  7. from sqlalchemy import create_engine

  1. from sqlalchemy.ext.declarative import
    declarative_base

  2. from sqlalchemy import
    Column,Integer,String

  3.  

  4. # echo=True打字与印刷新闻

  5. engine = create_engine(“mysql+pymysql://root:123456@192.168.31.134/test_db”,

  1.                        encoding=’utf-8′,echo=True)
  1.  

  2. # 生成orm基类

  3. Base = declarative_base()

  4.  

  5. class
    User(Base):

  6.     # 表名

  7.     __tablename__ = ‘USER’

  8.     # 定义字段ID,并安装为主键

  9.     ID =
    Column(Integer,primary_key=True)

  10.     NAME = Column(String(32))

  11.     PASSWORD = Column(String(64))

  1. # 创造表结构

  2. Base.metadata.create_all(engine)

除开上边的创造表之外,还有壹种创设表的不二等秘书籍。

  1. __author__ = ‘Golden’

  2. #!/usr/bin/env python3

  3. # -*- coding:utf-8 -*-

  4.  

  5. import sqlalchemy

  6.  

  7. from sqlalchemy import
    create_engine,Table,MetaData,Column,Integer,String,ForeignKey

  1. from sqlalchemy.orm import mapper
  1.  

  2. engine = create_engine(“mysql+pymysql://root:123456@192.168.31.134/test_db”,

  1.                        encoding=’utf-8′,echo=True)
  1. metadata = MetaData()

  2.  

  3. user = Table(‘USER_TABLE’,metadata,

  1.              Column(‘ID’,Integer,primary_key=True),
  1.              Column(‘NAME’,String(50)),
  1.              Column(‘FULLNAME’,String(50)),
  1.              Column(‘PASSWORD’,String(12))
  1.              )

  2.  

  3.  

  4. class
    User(object):

  5.     def
    __init__(self,name,fullname,password):

  6.         self.name = name

  7.         self.fullname = fullname

  1.         self.password = password
  1.  

  2. mapper(User,user)

  3.  

  4. # 成立表结构

  5. metadata.create_all(engine)

率先种办法创制的表是基于第壹种办法的再封装。

使用O大切诺基M创立一条数据。

  1. __author__ = ‘Golden’

  2. #!/usr/bin/env python3

  3. # -*- coding:utf-8 -*-

  4.  

  5. import sqlalchemy

  6. from sqlalchemy import
    create_engine,Column,Integer,String

  7. from sqlalchemy.orm import sessionmaker

  1. from sqlalchemy.ext.declarative import
    declarative_base

  2.  

  3. engine = create_engine(“mysql+pymysql://root:123456@192.168.31.134/test_db”,

  1.                        encoding=’utf-8′,echo=True)
  1. Base = declarative_base()

  2.  

  3. class
    User(Base):

  4.     __tablename__ = ‘USER’

  5.     ID =
    Column(Integer,primary_key=True)

  6.     NAME = Column(String(32))

  7.     PASSWORD = Column(String(64))

  1.  

  2. Base.metadata.create_all(engine)

  1. # 创立与数据库的会话session class,注意这里再次来到给session的是贰个class,不是实例
  1. Session_class =
    sessionmaker(bind=engine)

  2. # 生成session实例

  3. Session = Session_class()

  4. # 生成要开创的数额对象

  5. user_obj = User(NAME=”Golden”,PASSWORD=”123456″)

  6. # 此时还未有成立对象

  7. print(user_obj.NAME,user_obj.ID)

  1. # 把供给创建的数目对象加多到session
  1. Session.add(user_obj)

  2. # 此时还并未有制造对象

  3. print(user_obj.NAME,user_obj.ID)

  1. # 创制数量,统1提交

  2. Session.commit()

查询、修改

  1. __author__ = ‘Golden’

  2. #!/usr/bin/env python3

  3. # -*- coding:utf-8 -*-

  4.  

  5. import sqlalchemy

  6. from sqlalchemy import
    create_engine,Column,Integer,String

  7. from sqlalchemy.ext.declarative import
    declarative_base

  8. from sqlalchemy.orm import sessionmaker

  1. engine = create_engine(“mysql+pymysql://root:123456@192.168.31.134/test_db”,
  1.                        encoding=’utf-8′,echo=False)
  1. Base = declarative_base()

  2. class
    User(Base):

  3.     __tablename__ = ‘USER’

  4.     ID =
    Column(Integer,primary_key=True)

  5.     NAME = Column(String(32))

  6.     PASSWORD = Column(String(64))

  1.  

  2.     def __repr__(self):

  3.         return “<NAME : %s | PASSWORD : %s>”
    %(self.NAME,self.PASSWORD)

  4.  

  5. Session_class =
    sessionmaker(bind=engine)

  6. Session = Session_class()

  7. # first 查出NAME=’戈尔德en’的第壹个

  1. my_user =
    Session.query(User).filter_by(NAME=’Golden’).first()

  2. print(my_user.NAME,my_user.PASSWORD)

  1. # NAME=’Golden’

  2. data =
    Session.query(User).filter_by(NAME=’Golden’).all()

  3. print(data[0].PASSWORD)

  4. #all 查出全部

  5. data_2 =
    Session.query(User).filter_by().all()

  6. print(data_2)

  7. data_3 =
    Session.query(User).filter(User.ID == 1).all()

  8. print(data_3)

  9. data_4 =
    Session.query(User).filter_by(ID=1).all()

  10. print(data_4)

  11. # 多规范化查询

  12. data_5 =
    Session.query(User).filter(User.ID > 1).filter(User.ID <
    4).all()

  13. print(data_5)

  14. data_6 =
    Session.query(User).filter().first()

  15. print(data_6)

  16. # 修改

  17. data_6.NAME = ‘zhangsan’

  18. data_6.PASSWORD = ‘110’

  19. # 提交

  20. Session.commit()

回滚

  1. __author__ = ‘Golden’

  2. #!/usr/bin/env python3

  3. # -*- coding:utf-8 -*-

  4.  

  5. import sqlalchemy

  6. from sqlalchemy import
    create_engine,Column,Integer,String

  7. from sqlalchemy.ext.declarative import
    declarative_base

  8. from sqlalchemy.orm import sessionmaker

  1.  

  2. engine = create_engine(“mysql+pymysql://root:123456@192.168.31.134/test_db”,

  1.                        encoding=’utf-8′,echo=False)
  1. Base = declarative_base()

  2.  

  3. class
    User(Base):

  4.     __tablename__ = ‘USER’

  5.     ID =
    Column(Integer,primary_key=True)

  6.     NAME = Column(String(32))

  7.     PASSWORD = Column(String(64))

  1.  

  2.     def __repr__(self):

  3.         return “<ID : %s | NAME : %s | PASSWORD :
    %s>” %(self.ID,self.NAME,self.PASSWORD)

  4.  

  5. Session_class =
    sessionmaker(bind=engine)

  6. Session = Session_class()

  7.  

  8. my_user =
    Session.query(User).filter_by(ID=1).first()

  9. my_user.NAME = ‘Mark’

  10.  

  11. fake_user =
    User(NAME=’Merry’,PASSWORD=’999999′)

  12. Session.add(fake_user)

  13. # 查看刚刚加多和修改的数据

  14. print(Session.query(User).filter(User.NAME.in_([‘Merry’,’Mark’])).all())

  1. # rollback

  2. Session.rollback()

  3. # 再度查询

  4. print(Session.query(User).filter(User.NAME.in_([‘Merry’,’Mark’])).all())

总计和分组

  1. __author__ = ‘Golden’

  2. #!/usr/bin/env python3

  3. # -*- coding:utf-8 -*-

  4.  

  5. import sqlalchemy

  6. from sqlalchemy import
    create_engine,Column,Integer,String,func

  7. from sqlalchemy.ext.declarative import
    declarative_base

  8. from sqlalchemy.orm import sessionmaker

  1.  

  2. engine = create_engine(“mysql+pymysql://root:123456@192.168.31.134/test_db”,

  1.                        encoding=’utf-8′,echo=False)
  1.  

  2. Base = declarative_base()

  3.  

  4.  

  5. class
    User(Base):

  6.     __tablename__ = ‘USER’

  7.     ID =
    Column(Integer,primary_key=True)

  8.     NAME = Column(String(32))

  9.     PASSWORD = Column(String(64))

  1.  

  2.     def __repr__(self):

  3.         return “<ID : %s | NAME : %s | PASSWORD :
    %s>” %(self.ID,self.NAME,self.PASSWORD)

  4.  

  5. Session_class =
    sessionmaker(bind=engine)

  6. Session = Session_class()

  7. # 统计ha开头的NAME个数

  8. print(Session.query(User).filter(User.NAME.like(“ha%”)).count())

  9. # 分组

  10. print(Session.query(User.NAME,func.count(User.NAME)).group_by(User.NAME).all())

连表

  1. __author__ = ‘Golden’

  2. #!/usr/bin/env python3

  3. # -*- coding:utf-8 -*-

  4.  

  5. import sqlalchemy

  6. from sqlalchemy import
    create_engine,Column,Integer,String,DATE

  7. from sqlalchemy.orm import sessionmaker

  1. from sqlalchemy.ext.declarative import
    declarative_base

  2.  

  3. engine = create_engine(“mysql+pymysql://root:123456@192.168.31.134/test_db”,

  1.                        encoding=’utf-8′,echo=True)
  1. Base = declarative_base()

  2.  

  3. class
    User(Base):

  4.     __tablename__ = ‘USER’

  5.     ID =
    Column(Integer,primary_key=True)

  6.     NAME = Column(String(32))

  7.     PASSWORD = Column(String(64))

  1.  

  2.     def __repr__(self):

  3.         return “<ID :%s | NAME : %s | PASSWORD :
    %s>” %(self.ID,self.NAME,self.PASSWORD)

  4.  

  5.  

  6. class
    Student(Base):

  7.     __tablename__ = ‘STUDENT’

  1.     ID =
    Column(Integer,primary_key=True)

  2.     NAME =
    Column(String(32),nullable=False)

  3.     REGISTER_DATE =
    Column(DATE,nullable=False)

  4.     GENDER =
    Column(String(32),nullable=False)

  5.  

  6.     def __repr__(self):

  7.         return “<NAME : %s | PASSWORD : %s>”
    %(self.NAME,self.REGISTER_DATE)

  8.  

  9. Base.metadata.create_all(engine)

  1. Session_class =
    sessionmaker(bind=engine)

  2. Session = Session_class()

  3.  

  4. # 外联

  5. print(Session.query(User,Student).filter(User.ID
    == Student.ID).all())

  6. # 三个表必须有外键关联本事运用 Can’t
    find any foreign key relationships between ‘A’ and ‘B’

  7. print(Session.query(User).join(Student).all())

  1. print(Session.query(User).join(Student,isouter=True).all())
  1. Session.commit()

贯彻八个表的外键关联

  1. __author__ = ‘Golden’

  2. #!/usr/bin/env python3

  3. # -*- coding:utf-8 -*-

  4. import sqlalchemy

  5. from sqlalchemy import
    create_engine,Column,Integer,String,DATE,ForeignKey

  6. from sqlalchemy.orm import
    sessionmaker,relationship

  7. from sqlalchemy.ext.declarative import
    declarative_base

  8.  

  9. engine = create_engine(“mysql+pymysql://root:123456@192.168.31.134/test_db”,

  1.                        encoding=’utf-8′,echo=False)
  1. Base = declarative_base()

  2.  

  3. class
    Student(Base):

  4.     __tablename__ = ‘student’

  1.     id =
    Column(Integer,primary_key=True)

  2.     name =
    Column(String(32),nullable=False)

  3.     register_date =
    Column(DATE,nullable=False)

  4.  

  5.     def __repr__(self):

  6.         return “<name : %s | register_date :
    %s>”%(self.name,self.register_date)

  7.  

  8.  

  9. class
    StudyRecord(Base):

  10.     __tablename__ = “study_record”

  11.     id =
    Column(Integer,primary_key=True)

  12.     day =
    Column(Integer,nullable=False)

  13.     status =
    Column(String(32),nullable=False)

  14.     # 创立外键

  15.     stu_id =
    Column(Integer,ForeignKey(“student.id”))

  16.     #

  17.     student = relationship(“Student”,backref=”my_study_record”)

  18.  

  19.     def __repr__(self):

  20.        return “<%s day :%s | status :
    %s>”%(self.student.name,self.day,self.status)

  21. # 成立表结构

  22. Base.metadata.create_all(engine)

  1. # 创设与数据库的会话session

  2. Session_class =
    sessionmaker(bind=engine)

  3. # 生成session实例

  4. session = Session_class()

  5.  

  6. “””增加数据

  7. s1 = Student(name=”Golden”,register_date=”2017-12-24″)

  8. s2 = Student(name=”Jack”,register_date=”2017-11-13″)

  9. s3 = Student(name=”Rain”,register_date=”2017-10-11″)

  10. s4 = Student(name=”Eric”,register_date=”2017-07-07″)

  11.  

  12. study_obj1 =
    StudyRecord(day=1,status=”Yes”,stu_id=1)

  13. study_obj2 =
    StudyRecord(day=2,status=”No”,stu_id=1)

  14. study_obj3 =
    StudyRecord(day=3,status=”Yes”,stu_id=1)

  15. study_obj4 =
    StudyRecord(day=1,status=”Yes”,stu_id=2)

  16.  

  17. # 1回性全体成立

  18. session.add_all([s1,s2,s3,s4,study_obj1,study_obj2,study_obj3,study_obj4])

  1. “””

  2. stu_obj =
    session.query(Student).filter(Student.name == “Golden”).first()

  3. print(stu_obj)

  4. print(stu_obj.my_study_record)

  1. # 提交

  2. session.commit()

多外键关联

创建包罗多外键的表结构。

  1. __author__ = ‘Golden’

  2. #!/usr/bin/env python3

  3. # -*- coding:utf-8 -*-

  4.  

  5. from sqlalchemy.orm import relationship

  1. from sqlalchemy import
    create_engine,Column,Integer,String,DATE,ForeignKey

  2. from sqlalchemy.ext.declarative import
    declarative_base

  3.  

  4. Base = declarative_base()

  5.  

  6. class
    Customer(Base):

  7.     __tablename__ = ‘customer’

  1.     id =
    Column(Integer,primary_key=True)

  2.     name = Column(String(64))

  3.  

  4.     billing_address_id =
    Column(Integer,ForeignKey(“address.id”))

  5.     shipping_address_id =
    Column(Integer,ForeignKey(“address.id”))

  6.  

  7.     billing_address =
    relationship(“Address”,foreign_keys=[billing_address_id])

  1.     shipping_address =
    relationship(“Address”,foreign_keys=[shipping_address_id])
  1.  

  2. class
    Address(Base):

  3.     __tablename__ = ‘address’

  1.     id =
    Column(Integer,primary_key=True)

  2.     street = Column(String(64))

  3.     city = Column(String(64))

  4.     state = Column(String(64))

  5.  

  6.     def __repr__(self):

  7.         return self.street

  8.  

  9. engine = create_engine(“mysql+pymysql://root:123456@192.168.31.134/test_db”,

  1.                        encoding=’utf-8′,echo=False)
  1. # 成立表结构

  2. # Base.metadata.create_all(engine)

插入数据和查询。

  1. __author__ = ‘Golden’

  2. #!/usr/bin/env python3

  3. # -*- coding:utf-8 -*-

  4.  

  5. import os,sys

  6. path =
    os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

  1. sys.path.append(path)

  2. from day11 import orm_many_fk

  3. from sqlalchemy.orm import sessionmaker

  1.  

  2. Session_class =
    sessionmaker(bind=orm_many_fk.engine)

  3. session = Session_class()

  4.  

  5. # 创立数据

  6. # addr1 =
    orm_many_fk.Address(street=”zhongshanroad”,city=”qiaokou”,state=’hankou’)

  7. # addr2 =
    orm_many_fk.Address(street=”dongyiroad”,city=”hongshan”,state=”wuchang”)

  8. # addr3 =
    orm_many_fk.Address(street=”guangshanroad”,city=”gaoxin”,state=”guanggu”)

  9. #

  10. #
    session.add_all([addr1,addr2,addr3])

  11. # c1 =
    orm_many_fk.Customer(name=”Golden”,billing_address=addr1,shipping_address=addr3)

  1. # c2 =
    orm_many_fk.Customer(name=”Jack”,billing_address=addr2,shipping_address=addr2)
  1. #

  2. # session.add_all([c1,c2])

  3.  

  4. # 查询数据

  5. obj =
    session.query(orm_many_fk.Customer).filter(orm_many_fk.Customer.name==”Golden”).first()

  6. print(obj.name,obj.billing_address,obj.shipping_address)

  1.  

  2. session.commit()

多对多关系

成立多对多关联表

  1. __author__ = ‘Golden’

  2. #!/usr/bin/env python3

  3. # -*- coding:utf-8 -*-

  4.  

  5. from sqlalchemy import
    Table,Column,Integer,String,DATE,ForeignKey,create_engine

  6. from sqlalchemy.orm import
    relationship,sessionmaker

  7. from sqlalchemy.ext.declarative import
    declarative_base

  8.  

  9. engine = create_engine(“mysql+pymysql://root:123456@192.168.31.134/test_db”,

  1.                        encoding=’utf-8′,echo=False)
  1.  

  2. Base = declarative_base()

  3.  

  4. book_m2m_author =
    Table(‘book_m2m_author’,Base.metadata,

  5.                         Column(‘book_id’,Integer,ForeignKey(‘books.id’)),

  1.                         Column(‘author_id’,Integer,ForeignKey(‘authors.id’)))
  1.  

  2. class
    Book(Base):

  3.     __tablename__ = ‘books’

  4.     id =
    Column(Integer,primary_key=True)

  5.     name = Column(String(64))

  6.     pub_date = Column(DATE)

  7.     authors =
    relationship(‘Author’,secondary=book_m2m_author,backref=’books’)

  1.  

  2.     def __repr__(self):

  3.         return self.name

  4.  

  5.  

  6. class
    Author(Base):

  7.     __tablename__ = ‘authors’

  1.     id =
    Column(Integer,primary_key=True)

  2.     name = Column(String(32))

  3.  

  4.     def __repr__(self):

  5.         return self.name

  6.  

  7. Base.metadata.create_all(engine)

  1. Session_class =
    sessionmaker(bind=engine)

  2. session = Session_class()

 

插入数据和查询

  1. __author__ = ‘Golden’

  2. #!/usr/bin/env python3

  3. # -*- coding:utf-8 -*-

  4.  

  5. import os,sys

  6. path =
    os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

  1. sys.path.append(path)

  2. from day11 import orm_m2m

  3. from sqlalchemy.orm import sessionmaker

  1.  

  2. Session_class =
    sessionmaker(bind=orm_m2m.engine)

  3. session = Session_class()

  4.  

  5. # 制造数据

  6. # b1 = orm_m2m.Book(name=”Python”)

  7. # b2 = orm_m2m.Book(name=”JAVA”)

  8. # b3 = orm_m2m.Book(name=”C++”)

  9. # b4 = orm_m2m.Book(name=”c#”)

  10. #

  11. # a1 = orm_m2m.Author(name=”Golden”)

  12. # a2 = orm_m2m.Author(name=”Jack”)

  13. # a3 = orm_m2m.Author(name=”Rain”)

  14. #

  15. # b1.authors = [a1,a2]

  16. # b2.authors = [a1,a2,a3]

  17. #

  18. #
    session.add_all([b1,b2,b3,b4,a1,a2,a3])

  19. # session.commit()

  20.  

  21. print(“通过书表查询关联的小编”.center(50,”*”))

  22. book_obj =
    session.query(orm_m2m.Book).filter_by(name=”JAVA”).first()

  23. print(book_obj.name,book_obj.authors)

  1. print(“通过小编表查询关联的书”.center(50,”*”))

  2. author_obj =
    session.query(orm_m2m.Author).filter_by(name=”Golden”).first()

  3. print(author_obj.name,author_obj.books)

  1.  

  2. #
    多对多删除,删除数据时绝不管book_m2m_author,sqlalchemy会自动删除相应的数目

  1. # 通过书删除小编

  2. book_obj.authors.remove(author_obj)

  1.  

  2. # 直接删除我

  3. author_obj2 =
    session.query(orm_m2m.Author).filter_by(name=”Jack”).first()

  4. session.delete(author_obj2)

  5. session.commit()

 

帮忙粤语

sqlalchemy设置编码字符集一定要在数据库访问的ULANDL上加码charset=utf八,不然数据库的连天就不是utf八的编码格式。

  1. # 帮衬普通话

  2. engine = create_engine(“mysql+pymysql://root:123456@192.168.31.134/test_db?charset=utf8”,echo=True)

相关文章