Python MySQL连接器错误诊断

时间:2017-12-05 01:01:24

标签: python mysql

CONTEXT

Ubuntu 16.04:Python MySQL连接器

观测

cursor.execute语句将目标记录追加到MySQL 5.5.8数据库。尝试附加到MySQL 8.0.3会导致以下错误:

>>> cursor.execute(add_scan, data_scan)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/dist-packages/mysql/connector/cursor.py", line 551, in execute
    self._handle_result(self._connection.cmd_query(stmt))
  File "/usr/local/lib/python2.7/dist-packages/mysql/connector/connection.py", line 490, in cmd_query
    result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
  File "/usr/local/lib/python2.7/dist-packages/mysql/connector/connection.py", line 395, in _handle_result
    raise errors.get_exception(packet)
mysql.connector.errors.DatabaseError: 1364 (HY000): Field 'scantime' doesn't have a default value

然后注释掉这一行,然后.py脚本完成执行而没有任何错误迹象。

问题

  • 问题只是新的MySQL 8数据库不兼容吗?
  • 可以以某种方式更新MySQL连接器吗?

1 个答案:

答案 0 :(得分:3)

默认情况下,其中一台服务器以严格模式运行,而另一台服务器则没有。如果服务器以严格模式运行(或者在连接中设置它)并且您尝试将NULL值插入到定义为NOT NULL的列中,则会出现#1364错误。如果没有严格模式,您的NULL值将替换为空字符串或0。

示例:

CREATE TABLE `test_tbl` (
 `id` int(11) NOT NULL,
 `someint` int(11) NOT NULL,
 `sometext` varchar(255) NOT NULL,
 `somedate` datetime NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

SET sql_mode = '';
INSERT INTO test_tbl(id) VALUES(1);
SELECT * FROM test_tbl;
+----+---------+----------+---------------------+
| id | someint | sometext | somedate            |
+----+---------+----------+---------------------+
|  1 |       0 |          | 0000-00-00 00:00:00 |
+----+---------+----------+---------------------+
SET sql_mode = 'STRICT_ALL_TABLES';
INSERT INTO test_tbl(id) VALUES(2);
#1364 - Field 'someint' doesn't have a default value 

来源:MySQL INSERT without having to specify every non-default field (#1067 - Invalid default value for 'table')

修复:更改该字段以删除非null或将其设置为默认值,例如CURRENT_TIMESTAMP