本文實例講述了Python利用sqlacodegen自動生成ORM實體類。分享給大家供大家參考,具體如下:
在前面一篇《Python流行ORM框架sqlalchemy安裝與使用》我們是手動創建了一個名叫
Infos.py
的文件,然后定義了一個
News
類,把這個類作為和我們
news
數據表的映射。
from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() from sqlalchemy import Column, Integer, String class News(Base): # 表名稱 __tablename__ = 'news' # news表里id字段 id = Column(Integer, primary_key=True, autoincrement=True) # news表里title字段 title = Column(String(length=255), nullable=False)
現在我們來看看
sqlacodegen
這個工具,自動生成像上面那樣的類文件。
1、安裝sqlacodegen
#cd 項目虛擬環境 #執行 ./python3 -m pip install sqlacodegen
2、使用sqlacodegen生成案列
#注意還是在虛擬環境目錄下執行 ./sqlacodegen --tables fund --outfile ../../mappers/Found.py mysql+pymysql://root:root@localhost/test?charset=utf8
--tables
指定數據表名稱,我們給fund基金數據表生成。
--outfile
指定輸出文件名稱。
3、生成的 Fund.py 文件代碼如下:
# coding: utf-8 from sqlalchemy import Column, DateTime, Numeric, String from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() metadata = Base.metadata class Fund(Base): __tablename__ = 'fund' code = Column(String(50), primary_key=True) name = Column(String(255)) NAV = Column(Numeric(5, 4)) ACCNAV = Column(Numeric(5, 4)) updated_at = Column(DateTime)
這樣就不用手動寫啦。
更多關于Python相關內容感興趣的讀者可查看本站專題:《Python常見數據庫操作技巧匯總》、《Python數學運算技巧總結》、《Python數據結構與算法教程》、《Python函數使用技巧總結》、《Python字符串操作技巧匯總》、《Python入門與進階經典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設計有所幫助。
更多文章、技術交流、商務合作、聯系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號聯系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元
