将 INSERT SQL 语句的无效值更改为 None 但出现 "Data Truncated" 错误
Changing invalid value to None for INSERT SQL statement but getting "Data Truncated" error
我在 MySQL table 中有一个 FLOAT
列,我试图使用 Python 脚本填充它。大多数时候,我使用的数据值都是有效的浮点数,但有时它们是 "NaN"
。因此,当插入 table 时,我检查该值是否为 "NaN"
,如果是,我将其设置为 None
,据我所知,在 NULL
中插入 table。这没有发生,我不确定为什么。
这里是 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()
这是 table:
的 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]
为什么会发生这种情况,我该如何解决?提前谢谢你。
看过这个问题,但我的问题略有不同,这个问题没有答案:Unable to use None (NULL) values in python mysql.connector in prepared INSERT statement
您只需删除 VALUES
参数列表中的 "
。
将您的插入语句更改为:
sql_insert = ('INSERT INTO langmuir_result(scan_data_id, plasma_potential, floating_potential)'
'VALUES(%s, %s, %s)')
它将按预期工作。
我在 MySQL table 中有一个 FLOAT
列,我试图使用 Python 脚本填充它。大多数时候,我使用的数据值都是有效的浮点数,但有时它们是 "NaN"
。因此,当插入 table 时,我检查该值是否为 "NaN"
,如果是,我将其设置为 None
,据我所知,在 NULL
中插入 table。这没有发生,我不确定为什么。
这里是 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()
这是 table:
的 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]
为什么会发生这种情况,我该如何解决?提前谢谢你。
看过这个问题,但我的问题略有不同,这个问题没有答案:Unable to use None (NULL) values in python mysql.connector in prepared INSERT statement
您只需删除 VALUES
参数列表中的 "
。
将您的插入语句更改为:
sql_insert = ('INSERT INTO langmuir_result(scan_data_id, plasma_potential, floating_potential)'
'VALUES(%s, %s, %s)')
它将按预期工作。