Python ORM框架之sqlalchemy

一、概念

什么是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.youkuaiyun.com/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 
The SQLAlchemy Object Relational Mapper presents a method of associating user-defined Python classes with database tables, and instances of those classes (objects) with rows in their corresponding tables. It includes a sys- tem that transparently synchronizes all changes in state between objects and their related rows, called a unit of work, as well as a system for expressing database queries in terms of the user defined classes and their defined relationships between each other. The ORM is in contrast to the SQLAlchemy Expression Language, upon which the ORM is constructed. Whereas the SQL Expression Language, introduced in SQL Expression Language Tutorial, presents a system of representing the primitive constructs of the relational database directly without opinion, the ORM presents a high level and abstracted pattern of usage, which itself is an example of applied usage of the Expression Language. While there is overlap among the usage patterns of the ORM and the Expression Language, the similarities are more superficial than they may at first appear. One approaches the structure and content of data from the perspective of a user-defined domain model which is transparently persisted and refreshed from its underlying storage model. The other approaches it from the perspective of literal schema and SQL expression representations which are explicitly composed into messages consumed individually by the database. A successful application may be constructed using the Object Relational Mapper exclusively. In advanced situations, an application constructed with the ORM may make occasional usage of the Expression Language directly in certain areas where specific database interactions are required. The following tutorial is in doctest format, meaning each >>> line represents something you can type at a Python command prompt, and the following text represents the expected return value.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值