无法将 None 插入 mysql 整数字段

Can't insert None into mysql int field

我需要将一个 int 或 None 插入到 MySql int 字段(可为空)。 这是我的代码:

cur = db.cursor()
contents = [None, 3]
for element in contents:
    print(element)
    cur.execute('insert into test.new_test (blubb) values (%s)', element)
db.commit()

当我不使用 None,而是使用另一个 int 时,这有效。我只是不明白,为什么 None 不起作用,我得到错误

pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '%s)' at line 1"),

尽管我为这句话找到了所有解决方案,但 %s 能够处理 None...
另外,是否有一种方法可以在不使用 for 循环的情况下一次添加整个列表(每个条目一个新行)?

在mysql中它应该是NULL所以你需要把它改成:

cur = db.cursor()
contents = ['NULL', 3]
for element in contents:
    print(element)
    cur.execute('insert into test.new_test (blubb) values (%s)', element)
db.commit()

编辑

要解决新问题,您可以将其更改为:

cur = db.cursor()
contents = [None, 3]
for element in contents:
    print(element)
    if element==None:
        cur.execute('insert into test.new_test (blubb) values (NULL)')
    else:
        cur.execute('insert into test.new_test (blubb) values (%s)', element)
db.commit()

另一种方法是像解释的那样更改严格模式 here

请用 NULL 替换 NONE。传送到 MySQL 服务器的命令应如下所示:

insert into test.new_test (blubb) values (NULL)

其中 blubb 是 table new_test 中的有效列,并且必须允许 NULL 值。

干杯,