ProgrammingError: nan can not be used with MySQL

  1. 该错误怎么发生的?

我们先在本地创建测试表:

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;

ProgrammingError: nan can not be used with MySQL_第1张图片
然后,我们尝试通过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, '[email protected]') ) 

cursor.execute(f"INSERT INTO users_test(username,email) VALUES (%s,%s)", (np.NAN, '[email protected]') )

ProgrammingError: nan can not be used with MySQL_第2张图片

# 改变策略:

cursor.execute(f"INSERT INTO users_test(username,email) VALUES (%s,%s)", (None, '[email protected]') )  # 可以

# 提交事务并关闭连接
engine.commit()

# 关闭engine:
engine.close()

成功!

进一步总结:

ProgrammingError: nan can not be used with MySQL_第3张图片
一定要转一下
ProgrammingError: nan can not be used with MySQL_第4张图片

你可能感兴趣的:(mysql,数据库)