代码之家  ›  专栏  ›  技术社区  ›  octopusgrabbus ufukgun

如何在Python中为MySQL设置空值

  •  2
  • octopusgrabbus ufukgun  · 技术社区  · 8 年前

    这是我的SQL命令行版本。

    Welcome to the MySQL monitor.  Commands end with ; or \g.
    Your MySQL connection id is 122
    Server version: 5.0.95 Source distribution
    

    +---------------+-------------+------+-----+---------+-------+
    | Field         | Type        | Null | Key | Default | Extra |
    +---------------+-------------+------+-----+---------+-------+
    | Action        | char(1)     | NO   |     | R       |       | 
    | EndpointId    | int(11)     | NO   | MUL | NULL    |       | 
    | DeviceType    | smallint(6) | NO   |     | NULL    |       | 
    | ChannelNumber | smallint(6) | NO   |     | 0       |       | 
    | ActionDate    | date        | YES  |     | NULL    |       | 
    | InsertDate    | date        | YES  |     | NULL    |       | 
    +---------------+-------------+------+-----+---------+-------+
    

    sql_cmd = \
                    """insert into cs_remove
                    (
                    Action, EndpointId, DeviceType, ChannelNumber, ActionDate, InsertDate
                    )
                    VALUES 
                    (
                    %s, %s, %s, %s, %s, %s
                    )
                    """
    
                print(base_date)
                sql_data = ('R', ept_id, ept_type, ept_ch, "NULL", base_date);
    

    该示例最后将0000-00-00放入日期字符串。我想要空值。我可以从mysql命令行执行此操作,但不能从Python执行。任何帮助都将不胜感激。

    1 回复  |  直到 8 年前
        1
  •  5
  •   sadmicrowave    8 年前

    你应该使用 None NULL 您试图插入的mysql值。像这样:

    sql_data = ('R', ept_id, ept_type, ept_ch, base_date, None);
    

    以下是另一篇关于这个问题的帖子: https://bytes.com/topic/python/answers/166025-python-mysql-insert-null

    以及这篇文章: How can I insert NULL data into MySQL database with Python?