ProgrammingError: nan can not be used with MySQL
- 该错误怎么发生的?
我们先在本地创建测试表:
CREATE TABLE `users_test` (
`id` int NOT NULL AUTO_INCREMENT COMMENT '主键',
`trade_account` varchar(50) DEFAULT NULL COMMENT '交易账号',
`username` varchar(50) DEFAULT NULL,
`email` varchar(100) DEFAULT NULL,
`updated_at` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
SELECT * FROM users_test;
然后,我们尝试通过Python往里面写数:
import pymysql
engine = pymysql.connect(host="xxx.138.xxx.216", user="root",port=3306, password="xxxxxxMoH0Oj", database="xxxx", charset="utf8")
# cursor.execute(f"INSERT INTO users_test(username,email) VALUES (%s,%s)", (math.nan, 'TEST@QQ.COM') )
cursor.execute(f"INSERT INTO users_test(username,email) VALUES (%s,%s)", (np.NAN, 'TEST@QQ.COM') )
# 改变策略:
cursor.execute(f"INSERT INTO users_test(username,email) VALUES (%s,%s)", (None, 'TEST@3Q.COM') ) # 可以
# 提交事务并关闭连接
engine.commit()
# 关闭engine:
engine.close()
成功!
进一步总结:
一定要转一下