You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python操作MySQL插入数据时post_id值异常致主键重复错误求助

解决MySQL插入时主键post_id自动变为2147483647的重复键错误

问题描述

我正在使用CustomTkinter框架和MySQL数据库开发一个社交媒体克隆项目,添加帖子时通过mysql.connector模块的execute()函数插入数据,代码如下:

import mysql.connector

AddPost_conn = mysql.connector.connect(host="localhost",user="root",password="",database="codegram")
AddPost_conn_cursor = AddPost_conn.cursor()

AddPost_conn_cursor.execute("INSERT INTO post(sno,user_id,post_id,post_content) VALUES (2,1234567890,123456789156,'Hello man!')")
AddPost_conn.commit()
AddPost_conn.close()

执行代码时出现错误:

mysql.connector.errors.IntegrityError: 1062 (23000): Duplicate entry '2147483647' for key 'PRIMARY'

其中post_id列是主键约束,不清楚执行代码时post_id的值为何会发生变化,希望得到解决方法。

问题原因

你插入的post_id值123456789156超出了MySQL中INT类型的最大值(2147483647),MySQL会自动将超出范围的数值截断为该类型的最大值,当这个截断后的值已经存在于主键列中时,就会触发重复键约束错误。

解决方法

1. 修改post_id列的数据类型

将post_id的字段类型从INT改为BIGINT,BIGINT支持的最大值为9223372036854775807,足以容纳你要插入的数值。执行以下SQL语句:

ALTER TABLE post MODIFY COLUMN post_id BIGINT PRIMARY KEY;

2. 验证插入逻辑

修改字段类型后,重新执行你的Python插入代码,此时123456789156会被正确存储,不会被截断。

3. 推荐优化:使用自增主键

如果post_id不需要手动指定,建议将其设置为自增主键,避免手动输入数值带来的范围错误或重复问题:

ALTER TABLE post MODIFY COLUMN post_id BIGINT AUTO_INCREMENT PRIMARY KEY;

对应的Python代码可以省略post_id的插入操作,由MySQL自动生成唯一主键:

import mysql.connector

AddPost_conn = mysql.connector.connect(host="localhost",user="root",password="",database="codegram")
AddPost_conn_cursor = AddPost_conn.cursor()

# 省略post_id字段,由数据库自动生成主键值
AddPost_conn_cursor.execute("INSERT INTO post(sno,user_id,post_content) VALUES (2,1234567890,'Hello man!')")
AddPost_conn.commit()
AddPost_conn.close()

内容的提问来源于stack exchange,提问作者Abbilaash

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 04:00:16