【问题标题】:How to have a null value for MySQL in Python如何在 Python 中为 MySQL 设置空值
【发布时间】:2017-09-15 16:45:08
【问题描述】:

这是我的 SQL 命令行版本。

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

我有一个表,从 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    |       | 
+---------------+-------------+------+-----+---------+-------+

如何将空值放入插入查询字符串?换句话说,我不知道如何在 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);

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

【问题讨论】:

  • 尝试使用None

标签: python mysql python-2.7 null mysql-python


【解决方案1】:

您应该在 python 中使用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?

【讨论】:

  • 我有一种感觉,它可能是无。我去试试这个。谢谢。
猜你喜欢
  • 2015-07-10
  • 2011-03-07
  • 1970-01-01
  • 1970-01-01
  • 2022-11-12
  • 1970-01-01
  • 2022-12-04
  • 2011-07-07
  • 1970-01-01
相关资源
最近更新 更多