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

Python通过输入向数据库插入用户时内容被拆分为单个字符的问题

问题解决:将完整用户名作为单条记录插入数据库

问题根源

你代码里的for key, person in enumerate(question):会遍历输入字符串的每一个字符——因为Python中字符串属于可迭代对象,所以循环会把每个字符单独作为一条记录插入,最终导致名字被拆分成多条数据。

修正代码

直接移除循环,将整个输入的名字作为单条记录插入。同时必须使用参数化查询,这既能避免SQL注入风险,也能规避字符串转义的问题:

cr = db.cursor()

cr.execute("CREATE TABLE if not exists users (user_id int,name text)")
cr.execute("CREATE TABLE if not exists skills (name text,progress int, user_id int )")

question = input("enter your name")

# 生成不重复的user_id:先查当前最大id,再加1
cr.execute("SELECT COALESCE(MAX(user_id), 0) FROM users")
max_user_id = cr.fetchone()[0]
new_user_id = max_user_id + 1

# 参数化插入整条记录
cr.execute("INSERT INTO users(user_id, name) VALUES (%s, %s)", (new_user_id, question))

db.commit()
db.close()

优化建议

如果你的数据库支持自增主键(比如MySQL的AUTO_INCREMENT、SQLite的AUTOINCREMENT),可以把user_id设为自增列,省去手动生成id的步骤:

# 创建表时将user_id设为自增主键
cr.execute("CREATE TABLE if not exists users (user_id int AUTO_INCREMENT PRIMARY KEY,name text)")
# 插入时无需指定user_id
cr.execute("INSERT INTO users(name) VALUES (%s)", (question,))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 19:20:35