文章摘要
这篇文章介绍了使用SQLAlchemy创建数据库表的三要素:引擎、基类和元素。通过`sqlalchemy`模块,可以定义数据库表的结构,包括表名和字段信息。文章详细说明了如何通过`create_engine`获取数据库连接,定义基类`declarative_base()`,以及使用`Column`定义字段类型和属性(如主键、长度等)。最后,通过`Base.metadata.create_all(engine)`创建实际的数据表。文章还简要提到了相关扩展和基础教程,帮助读者进一步了解SQLAlchemy的使用方法。
python之sqlalchemy创建表的实例详解
通过sqlalchemy创建表需要三要素:引擎,基类,元素
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column,Integer,String
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__=’user’
id=Column(Integer,primary_key=True)
name=Column(String(32))
password=Column(String(64))
通过基本元素:
__tablename__:指定表名
Column:行声明,可指定主键
Integer:数据类型
String:数据类型,可指定长度
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时间戳及密码管理实现代码详解
© 版权声明
文章版权归作者所有,未经允许请勿转载。



