我在MySQL表中有一个FLOAT
列,我正在尝试使用Python脚本填充该列。大多数时候,我使用的数据都是有效的浮点数,但有时它们是"NaN"
的。因此,在插入表中时,我检查该值是否"NaN"
,如果是,则将其设置为None
据我了解,该值作为NULL
插入表中。这没有发生,我不确定为什么。
以下是 Python 代码:
for row in zip(plasma_potential_set, floating_potential_set):
row = [scan_result_id] + list(row)
for i in range(len(row)):
if str(row[i]).lower() == "nan":
row[i] = None
sql_insert = ('INSERT INTO langmuir_result(scan_data_id,
plasma_potential, floating_potential)'
'VALUES(%s, "%s", "%s")')
cursor.execute(sql_insert, row)
mydb.commit()
cursor.close()
下面是该表的 CREATE 语句:
CREATE TABLE result (result_id INT auto_increment, scan_data_id INT,
plasma_potential FLOAT, floating_potential FLOAT, PRIMARY KEY (result_id));
这是我得到的错误:
_mysql_exceptions.DataError: (1265, "Data truncated for column 'plasma_potential' at row 1")
以下是我将任何无效值设置为 None 后该行的外观:
[1, None, 17.4651]
为什么会发生这种情况,我该如何解决?提前谢谢你。
看过这个问题,但我的问题略有不同,这个问题没有答案:无法在准备好的 INSERT 语句中使用 python mysql.connector 中的 None (NULL( 值
您只需删除VALUES
参数列表中的"
。 将插入语句更改为:
sql_insert = ('INSERT INTO langmuir_result(scan_data_id, plasma_potential, floating_potential)'
'VALUES(%s, %s, %s)')
它将按预期工作。