Python 如何在 SQLAlchemy 中插入 NULL 值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32959336/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 12:32:54  来源:igfitidea点击:

How to insert NULL value in SQLAlchemy?

pythonsqlalchemy

提问by bodacydo

I've a Tablewith the following column:

我有一个Table以下列:

Column('type', String(128))

How do I set this column to NULL when inserting a new row in database?

在数据库中插入新行时,如何将此列设置为 NULL?

I tried doing this:

我尝试这样做:

self.type = NULL;

There is no NULLtype in Python so I don't know how to do it.

NULLPython 中没有类型,所以我不知道该怎么做。

采纳答案by Hayk Davtyan

Instead of trying

而不是尝试

self.type = NULL

try as Yaroslav Admin suggested

按照Yaroslav 管理员的建议尝试

self.type = None

As Python's equivalent for NULL is None.

因为 Python 的 NULL 等价物是 None。

回答by omeanwell

I know this is an old thread but this worked for me

我知道这是一个旧线程,但这对我有用

self.type = sqlalchemy.sql.null()

回答by Ilja Everil?

As the other answers have pointed out, an explicit NULL can be inserted by passing None, or in case of SQLAlchemy a null()construct, as the value. In fact PEP-249 "DB-API v2.0" clearly states this in "Type Objects and Constructors":

正如其他答案所指出的那样,可以通过传递None或在 SQLAlchemynull()构造的情况下作为值插入显式 NULL 。事实上,PEP-249 "DB-API v2.0" 在"Type Objects and Constructors" 中清楚地说明了这一点:

SQL NULL values are represented by the Python Nonesingleton on input and output.

SQL NULL 值由None输入和输出的 Python单例表示。

As a third option one can simply omit the column, if it is nullable:

作为第三种选择,如果列可以为空,则可以简单地省略该列:

t = Table('t', metadata,
          Column('a', Integer),
          Column('b', Integer))

stmt = t.insert().values(a=1)
engine.execute(stmt)

would effectively insert a new row (1, NULL)in the table t, because a value was not provided for column b. The same applies for mapped classes, which I suppose the original question is actually using (because of the self):

将有效地(1, NULL)在表中插入一个新行t,因为没有为列提供值b。这同样适用于映射类,我认为原始问题实际上正在使用(因为self):

class T(Base):
    __tablename__ = 't'
    id = Column(Integer, primary_key=True)
    a = Column(Integer)
    b = Column(Integer)

session.add(T(a=1))
session.commit()

again effectively results in (default, 1, NULL)being inserted.

再次有效地导致(default, 1, NULL)被插入。