mysql timestamp为0值时,python读取后的对象为None

MySQL数据表中,如果timestamp类型的字段,值为0, python从数据库读取数据后,得到对象是什么类型,是否为None呢?

下面来测试下。

创建数据表

首先创建数据表,其中字段pr_rule_update_time为timestamp类型,值为0.

CREATE TABLE `orange_service` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `service_group_name` varchar(100) NOT NULL,
  `pr_rule` tinyint(3) NOT NULL DEFAULT '-1',
  `pr_rule_update_time` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `pr_rule_reason` varchar(256) NOT NULL DEFAULT '',
  `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  UNIQUE KEY `uk_group_host_port` (`service_group_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

插入数据

向数据表中插入一条记录。

mysql> insert into orange_service(service_group_name, pr_rule, pr_rule_reason) values('test', 0, '');
Query OK, 1 row affected (0.03 sec)

mysql> select * from orange_serviceG
*************************** 1. row ***************************
                        id: 1
        service_group_name: test
            promotion_rule: 0
promotion_rule_update_time: 0000-00-00 00:00:00
     promotion_rule_reason:
               create_time: 2019-10-08 16:52:19
1 row in set (0.03 sec)

python 读取数据

通过python读取数据。

import MySQLdb

host = "10.66.99.88"
port = 5002
sql = "select * from cmdb.orange_service"
user = "test"
passwd = "test123456"

conn = MySQLdb.connect(host=host, port=port, user=user,passwd=passwd, connect_timeout=2, charset="utf8")

cursor = conn.cursor()
cursor.execute(sql)

ret = cursor.fetchone()

print(ret)

cursor.close()
conn.close()

output:

(1, 'test', 0, None, '', datetime.datetime(2019, 10, 8, 16, 52, 19))

从输出可以看到,timestamp类型的字段,通过python读取后,值为None。

原文地址:https://www.cnblogs.com/lanyangsh/p/11665494.html