python之sqlalchemy創(chuàng)建表的實(shí)例詳解
通過sqlalchemy創(chuàng)建表需要三要素:引擎,基類,元素
from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column,Integer,String
引擎:也就是實(shí)體數(shù)據(jù)庫連接
engine = create_engine('mysql+pymysql://godme:godme@localhost/godme',encoding='utf-8',echo=True)
傳入?yún)?shù):數(shù)據(jù)庫類型+連接庫+用戶名+密碼+主機(jī),字符編碼,是否打印建表細(xì)節(jié)
基類:
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:數(shù)據(jù)類型
String:數(shù)據(jù)類型,可指定長(zhǎng)度
創(chuàng)建:
Base.metadata.create_all(engine)
基本過程:
1. 獲取實(shí)體數(shù)據(jù)庫連接
2. 創(chuàng)建類,繼承基類,用基本類型描述數(shù)據(jù)庫結(jié)構(gòu)
3. 基類調(diào)用類結(jié)構(gòu),根據(jù)描述在引擎上創(chuàng)建數(shù)據(jù)表
如有疑問請(qǐng)留言或者到本站社區(qū)交流討論,感謝閱讀,希望能幫助到大家,謝謝大家對(duì)本站的支持!
您可能感興趣的文章:- Python SQLAlchemy入門教程(基本用法)
- python SQLAlchemy的Mapping與Declarative詳解
- python SQLAlchemy 中的Engine詳解
- Python流行ORM框架sqlalchemy安裝與使用教程
- Python使用sqlalchemy模塊連接數(shù)據(jù)庫操作示例
- Python SqlAlchemy動(dòng)態(tài)添加數(shù)據(jù)表字段實(shí)例解析
- Python的Flask框架中使用Flask-SQLAlchemy管理數(shù)據(jù)庫的教程
- 在Python程序和Flask框架中使用SQLAlchemy的教程
- Python sqlalchemy時(shí)間戳及密碼管理實(shí)現(xiàn)代碼詳解