一、概念
什么是ORM框架?
ORM:Object Relation Mapping,最初主要描述的是程序中的Object对象和关系型数据库中Rlation关系(表)之间的映射关系,目前来说也是描述程序中对象和数据库中数据记录之间的映射关系的统称,是一种进行程序和数据库之间数据持久化的一种编程思想。
什么是sqlalchemy?
sqlalchemy是一个python语言实现的的针对关系型数据库的orm库。可用于连接大多数常见的数据库,比如MySQL、SQLite、mongodb,redis等。三方库,pip install sqlalchemy
二、具体使用方法
1. 数据库—表操作
创建数据库,创建表格,表格字段获取:
# -*- coding:utf-8 -*-
import os, random
from datetime import date
import sqlalchemy
from sqlalchemy.engine import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column
from sqlalchemy.types import String, Date, Float, Integer
from sqlalchemy import event, DDL
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
current_path = os.path.join(os.path.dirname(os.path.abspath(__file__)))
db_path = os.path.join(current_path, 'dbs', 'student.db')
print(db_path)
Base = declarative_base()
#字段说明: https://blog.csdn.net/gymaisyl/article/details/86508244
class User(Base):
__tablename__ = 'user'
id = Column(Integer, primary_key=True, autoincrement=True)#默认从1开始
name = Column(String(32), nullable=False)
age = Column(Integer, nullable=False)
birthday = Column(Date)
score = Column(Float)
def __repr__(self):
return self.name
def create_engin():
'''
创建数据库引擎
获取数据库中的表名列表,若表不存在,则新建
pymysql
mysql+pymysql://<username>:<password>@<host>/<dbname>[?<options>]
engine = create_engine("mysql+pymysql://root:123456@localhost:3306/db4?charset=utf8",
max_overflow=0, # 超过连接池大小外最多创建的连接
pool_size=5, # 连接池大小
pool_timeout=30, # 池中没有线程最多等待的时间,否则报错
pool_recycle=-1 # 多久之后对线程池中的线程进行一次连接的回收(重置)
echo = True # echo参数为True时,会显示每条执行的SQL语句,可以关闭 ",
max_overflow = 5)
sqlite3, sqlite3 python标准库
engine = create_engine('sqlite:///%s'%db_path)
'''
engine = create_engine('sqlite:///%s'%db_path)
db_insp