gpt4 book ai didi

mysql - 无法将 None 插入 mysql int 字段

转载 作者:行者123 更新时间:2023-11-29 06:42:09 25 4
gpt4 key购买 nike

我需要将 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

关于mysql - 无法将 None 插入 mysql int 字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51125524/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com