python - 通过声明性映射创建架构 : Base.metadata.create_all(engine) 不起作用

标签 python mysql sqlalchemy

这是一个看似简单的 sqlalchemy 荒谬问题!首先,这是我用于连接到 的配置文件数据库:

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
engine = create_engine('mysql://root:@localhost:3306/digi')

然后,我尝试创建一个名为“sale-history”的表:

from config import *
from sqlalchemy import *

class Sale(Base):
    __tablename__ = 'sale-history'
    order_id = column(Integer, primary_key= True)
    customer_id = column(Integer)
    item_id = column(Integer)       #froeign key with product list
    cartFinalize_dateTime = column(DATETIME)
    amount_ordrered = column(Integer)
    city_name = column(String(191))
    quantity_ordered = column(Integer)

    def __repr__(self):
        return "<Sale(city_name='%s')>" % (self.city_name)

Sale.__table__
Base.metadata.create_all(engine)

现在,我想知道的是

Sale.__table__

Base.metadata.create_all(engine)

我的代码不知道。更准确地说,这些并不在 pycharm 编辑器显示的建议选项中。调试代码不会引发任何错误(返回 0)。我应该做什么来创建表? 非常感谢您的考虑!

最佳答案

代码使用column来定义表中的列,但它应该使用Column(注意大写的“C”)。

一些提示/评论

  • 如果您避免使用 from module import * 习惯用法,Pycharm 可能会提供更好的支持。如果模块名称太长而无法输入,您可以为模块名称添加别名,例如 import sqlalchemy as sa
  • 您可以通过将 echo=True 传递给 create_engine 来查看引擎生成的 SQL
  • 带有连字符的表名需要用反引号引起来才有效。 Sqlalchemy 会自动执行此操作,但其他应用程序可能不会。使用下划线可能会更方便。

最终的代码可能如下所示:

配置

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()
engine = create_engine('mysql://root:@localhost:3306/test', echo=True)

型号

import sqlachemy as sa
import config


class Sale(Base): 
    __tablename__ = 'sale-history'
    order_id = sa.Column(sa.Integer, primary_key=True)
    customer_id = sa.Column(sa.Integer)   
    item_id = sa.Column(sa.Integer)       # foreign key with product list
    cartFinalize_dateTime = sa.Column(sa.DATETIME)
    amount_ordrered = sa.Column(sa.Integer)
    city_name = sa.Column(sa.String(191))
    quantity_ordered = sa.Column(sa.Integer)

    def __repr__(self):
        return "<Sale(city_name='%s')>" % (self.city_name)


Base.metadata.create_all(config.engine)

关于python - 通过声明性映射创建架构 : Base.metadata.create_all(engine) 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56361921/

相关文章:

python - 如何捕获 ThreadPoolExecutor() 中线程死亡的情况?

python - 绘制 scikit-learn (sklearn) SVM 决策边界/曲面

python - 无法在内部使用几何管理器网格。已经有由包管理的奴隶

Python - 如何提高小数的准确性?

python - 测试抛出 IntegrityError 的 SQLAlchemy 代码的正确方法是什么?

java - 如何在 Spring JPA for MySQL 中为 @Id @GeneratedValue 设置初始值?

php - 难以从 edmunds api 获取样式 ID

php - 使用 php 和 ajax 在谷歌饼图中处理事件

mysql - 外键和基本关系表

python - 使用 Python、SQLALchemy、Sqlite 设置/插入多对多数据库