如何在Python中为MySQL设置空值

oct*_*bus 2 python mysql null mysql-python python-2.7

这是我的 SQL 命令行版本。

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 122
Server version: 5.0.95 Source distribution
Run Code Online (Sandbox Code Playgroud)

我有一个表,在 Python 中,我想将最后一列写为空。最终,特定行的最后一列将获得一个日期戳,我将使用它作为不再处理该行的标志。

+---------------+-------------+------+-----+---------+-------+
| 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    |       | 
+---------------+-------------+------+-----+---------+-------+
Run Code Online (Sandbox Code Playgroud)

如何将 null 放入插入查询字符串中?换句话说,我不知道如何在 Python 查询字符串中表示 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);
Run Code Online (Sandbox Code Playgroud)

该示例最终将 0000-00-00 添加到日期字符串中。我想要 NULL。我可以从 mysql 命令行执行此操作,但不能从 Python 执行此操作。任何帮助,将不胜感激。

sad*_*ave 5

您应该使用Nonepython 中的值来表示NULL您尝试插入的 mysql 值。就像这样:

sql_data = ('R', ept_id, ept_type, ept_ch, base_date, None);
Run Code Online (Sandbox Code Playgroud)

这是对另一篇涉及此问题的帖子的引用:https://bytes.com/topic/python/answers/166025-python-mysql-insert-null

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