我正在使用python从一个文件插入mariadb表中的记录。输入文件有头。文件中的“填充”和“平均高度”列部分为空。我希望它在表中也是空值。表中的填充列设置为bigint(20),可以接受null值。我正在尝试下面的代码-
Table Definition -
CREATE TABLE `local_db`.`table_x` (
`Unique_code` varchar(50) NOT NULL,
`city` varchar(200) DEFAULT NULL,
`state` varchar(50) DEFAULT NULL,
`population` bigint(20) DEFAULT NULL,
`Avg_Height` double DEFAULT NULL,
`Govt` varchar(50) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
try:
connection = mysql.connector.connect(host='localhost',
database='local_db',
user='root',
password='root',
port = '3306')
input_file = "input_file"
csv_data = csv.reader(open(input_file))
next(csv_data)
cursor = connection.cursor()
for row in csv_data:
cursor.execute("""
INSERT INTO table_x(Unique_code,city,state,population,Avg_Height,Govt)
VALUES(%s,%s,%s,%s,%s,%s)
ON DUPLICATE KEY UPDATE city = VALUES(city),state = VALUES(state), \
population = VALUES(population),Avg_Height = VALUES(Avg_Height),Govt = VALUES(Govt)""")
connection.commit()
print(cursor.rowcount, "Record inserted successfully into table_x")
cursor.close()
except mysql.connector.Error as error:
print("Failed to insert record into table_x table {}".format(error))
finally:
if (connection.is_connected()):
connection.close()
print("MySQL connection is closed")
但我的错误是-
Failed to insert record into table_x table 1366 (22007): Incorrect integer value: '' for column `local_db`.`table_x`.`population` at row 1
MySQL connection is closed
请建议我可以在这里做什么代码更改来处理这种情况。
2条答案
按热度按时间ymzxtsji1#
你需要插入
null
而不是''
空字符串。这是演示。jchrr9hc2#
你需要插入
NULL
而不是空字符串。您可以预处理row
将空字符串转换为None
,具有相同的效果: