python之sqlalchemy创建表的实例详解(python元组与字典)学会了吗

随心笔谈12个月前发布 admin
70 0



python之sqlalchemy创建表的实例详解

通过sqlalchemy创建表需要三要素:引擎,基类,元素

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

引擎:也就是实体数据库连接

engine=create_engine(‘mysql+pymysql://godme:godme@localhost/godme’,encoding=’utf-8′,echo=True)

传入参数:数据库类型+连接库+用户名+密码+主机,字符编码,是否打印建表细节

基类:

Base=declarative_base()

元素:

class User(Base):
__tablename__=’user’
id=Column(Integer,primary_key=True)
name=Column(String(32))
password=Column(String(64))

通过基本元素:

__tablename__:指定表名
Column:行声明,可指定主键
Integer:数据类型
String:数据类型,可指定长度

创建:

Base.metadata.create_all(engine)

基本过程:

1. 获取实体数据库连接

2. 创建类,继承基类,用基本类型描述数据库结构

3. 基类调用类结构,根据描述在引擎上创建数据表

如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

您可能感兴趣的文章:Python SQLAlchemy入门教程(基本用法)python SQLAlchemy的Mapping与Declarative详解python SQLAlchemy 中的Engine详解Python流行ORM框架sqlalchemy安装与使用教程Python使用sqlalchemy模块连接数据库操作示例Python SqlAlchemy动态添加数据表字段实例解析Python的Flask框架中使用Flask-SQLAlchemy管理数据库的教程在Python程序和Flask框架中使用SQLAlchemy的教程Python sqlalchemy时间戳及密码管理实现代码详解

© 版权声明

相关文章