- Traditional database connection method: mysql (PyMySQL)
-
- ORM model: SQLAlchemy MyBatis, Hibernate
-
PyMySQL
- Install:
pip install pymysql
Simple to use
Use pymysql.connect to establish a database connection and execute SQL commands (the database needs to be built in advance):
import pymysql
db = pymysql.connect(
# mysql 地址
host='182.92.129.158',
# 账号和密码
user='tmp',
password='ceshiren.com',
# 数据库
db='tmp',
charset='utf8mb4'
)
if __name__ == '__main__':
with db.cursor() as cursor:
# 查看数据库中有多少表
sql = "show tables;"
# 执行 sql 语句
cursor.execute(sql)
# 查看所有数据
print(cursor.fetchall())
# 查询 name = aaaaaa 的数据
sql = "select * from test_case_table where name=%s"
cursor.execute(sql, ["aaaaaa"])
print(cursor.fetchall())
(('test_case_table',),)
(('aaaaaa', '新的测试用例', 'test_hello.py', 'def test'),)
ORM
Object-relational mapping (object-relational mapping) uses language features to operate the database, such as the operation of Python objects, the operation content will be mapped to the database.
SQLALchemy is an ORM framework under the Python programming language. The framework is built on the database API and uses relational object mapping for database operations.
Install
pip3 install SQLAlchemy
After the installation is complete, you can create a database connection:
engine = create_engine("mysql+pymysql://tmp:[email protected]/tmp?charset=utf8",echo=True,)
1.echo: When set to True, the ORM statement will be converted into a SQL statement for printing, which is generally available for debugging.
2. Field explanation:
3.mysql+pymysql: connection mode, using pymysql.
4.tmp:ceshiren.com: username:password.
5.182.92.129.158/tmp: database address and database name.
create database
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy.orm import declarative_base
engine = create_engine("mysql+pymysql://tmp:[email protected]/tmp?charset=utf8",
echo=True,
)
# 其子类将 Python 类和数据库表关联映射起来
Base = declarative_base()
# 继承 Base
class Users(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True)
name = Column(String(64), unique=True)
def __init__(self, name):
self.name = name
if __name__ == '__main__':
# 生成数据库表,如果有此库会忽略
Base.metadata.create_all(engine)
declarative_base() is a method internally encapsulated by SQLALchemy, which allows its subclasses to associate and map Python classes with database tables.
Add and check
SQLALchemy uses Session to create a session between the program and the database, and the addition, deletion, modification and query of data can be realized through the Session object.
from sqlalchemy.orm import sessionmaker
# 创建session
Session = sessionmaker(bind=engine)
session = Session()
# 添加新数据
add_user = Users("student1")
# 提交
session.add(add_user)
session.commit()
# 查询
result = session.query(Users).filter_by(name="student1").first()
print(result.id, result.name)
After the above code adds data, query it, and the results are as follows:
1 student1
The data persistence technology is introduced here first. You can try to do some exercises.
We will talk about cross-platform API docking later. Please continue to pay attention~