Python operates MySQL database through ORM


ORM way

The full name of ORM is Object Relational Mapping, that is, object relational mapping. Its realization idea is to map the data of the table in the relational database into objects, and display them in the form of objects, so that developers can convert operations on the database into operations on these objects. Therefore, its purpose is to facilitate developers to implement the operation of the database with object-oriented thinking


advantage: No need to use complex sql statements, and easy to understand, no need to maintain a large number of sql statements, the system automatically converts them into sql statements

Disadvantage: ORM method, low efficiency, when you need to operate data efficiently, you still need to use SQL statements

One, Python operation MySql

1.1 Read data

Code example:

from sqlalchemy.ext.declarative import declarative_base 
from sqlalchemy import Column,Integer,String,create_engine
from sqlalchemy.orm import sessionmaker

#生成基类 所有表构建的类都是基类之上的 继承这个基类
Base = declarative_base()

class Student(Base):
    __tablename__ ='student'#表名

    id = Column(Integer, primary_key=True)
    name = Column(String)
    age = Column(Integer,default=0)#默认0
    score = Column(Integer,default=60)#默认60

#创建引擎 相当于连接
engine = create_engine('mysql+pymysql://test:123456@localhost:3306/testdb')
DBSession = sessionmaker(engine)
session = DBSession()#必须实例化对象

#使用ORM方式对student表做一个查询
students = session.query(Student).limit(10)
for s in students:
    print(s.id,s.name,s.age,s.score)

session.close()#必须要关闭

Result display:
Insert picture description here

1.2 Insert data

The code is as follows (example):

#填入数据
#随机生成 两个字的姓名  年龄 分数 
for _ in range(10):
    s = Student(name=''.join(random.sample('张王天男别奥法妹大',2)),
                age=random.randint(16,22),score=random.randint(55,89))
    #add只是把对象加到session里面,最中执行是下面的commit()
    session.add(s)
#把添加的数据  整个让数据库执行,最终添加
session.commit()

Result display:
Insert picture description here

1.3 Conditional query

1.3.1 Query all

The code is as follows (example):

#条件查询
#查找所有(all())名字是男奥的同学并打印出来
students = session.query(Student).filter(Student.name =='男奥').all()
for s in students:
    #print(s)  只是输出对象
    print(s.id,s.name,s.age,s.score)

Result display:
Insert picture description here
Insert picture description here

1.3.2 Query individual

The code is as follows (example):

'''
students = session.query(Student).filter(Student.name =='王天').limit(1)
'''

students = session.query(Student).filter(Student.name =='王天').limit(2)

Result display:
Insert picture description here

1.3.3 Use conditions of limit(), all(), one()

When the name isonlyWhen you can use one(), that is, generallyPrimary keyUse one()【The primary key cannot be repeated
Use limit() when looking for individual required
data, use all() when looking for data in all data

Understand and master the difference between limit() and one() :

Even if limit(1), you should use the for loop to iteratively output data [The limit() function returns a list] The
one() function returns the object [one() is the only

1.4 Modify data

Code example:

#修改数据
student = session.query(Student).filter(Student.name =='Tom').one()
print(student.age)
student += 2
session.add(student)
session.commit()
student = session.query(Student).filter(Student.name =='Tom').one()
print(student.age)

before fixing:

Insert picture description here
After modification:
Insert picture description here
printout:
Insert picture description here


to sum up

问题1:NameError: name ‘random’ is not defined

Solution : add import random

Question 2: Failed to insert the Chinese name of the database (as shown in the figure)

I use the VS Code editor (this problem has always existed after using VS, until it was found to be solved after combining with the database)
Insert picture description here

Solution : After tossing for about two hours, (the online tutorial is of no use to my situation) finally adopted the ultimate method----->Uninstalling the newly installed
database. It is best to follow the online tutorial to uninstall it yourself.
Unclean uninstallation will cause the secondary installation to fail. MySql uninstallation tutorial
results show:

The Chinese name is a supplement to the successful insertion from the new installation after uninstallation
Insert picture description here
: Why does MySql fail to insert Chinese?

SHOW VARIABLES LIKE'character%'; //Use this command

In the figure below: Success should be as shown in the figure below.
Insert picture description here
Failure (before uninstallation): As shown in the figure below

In fact, as long aslatin1change intoutf8Yes (it is a complete change), but the online tutorial tried many ways to no avail, and finally had to uninstall and reinstall
Insert picture description here

Guess you like

Origin blog.csdn.net/HG0724/article/details/112332393