MySQL插入时Incorrect integer value错误求助:外键自动填充失败
问题原因
你当前的错误源于将一段SQL查询字符串当作普通字符串值传给了article_ID字段——数据库会把CAST(SELECT ID FROM article WHERE title = UDASSA) as INT当成纯文本,而非执行这段SQL逻辑,自然无法转换成整数。另外,直接拼接article.title还存在SQL注入风险,如果标题包含单引号等特殊字符,SQL语句会直接报错。
解决方法
推荐两种可靠方案,优先选第一种:
方案1:用lastrowid获取刚插入的文章ID
插入article表后,MySQL游标会自动保存刚生成的自增ID,直接通过mycursor.lastrowid获取即可,这是最准确且高效的方式:
mydb = mysql.connector.connect(host="localhost", user="...", password="...", database="knowledgebase") mycursor = mydb.cursor() # 插入article表 sql = "INSERT INTO article (title, author, summary, source) VALUES (%s, %s, %s, %s)" val = (article.title.strip(), ", ".join(article.authors), summary.strip(), url.strip()) mycursor.execute(sql, val) # 获取刚插入的文章自增ID new_article_id = mycursor.lastrowid mydb.commit() # 插入article_fulltext表,直接使用获取到的ID sql = "INSERT INTO article_fulltext (article_ID, body_text, html) VALUES (%s, %s, %s)" val = (new_article_id, article.text.strip(), article.html.strip()) mycursor.execute(sql, val) mydb.commit() mydb.close()
方案2:在INSERT语句中使用参数化子查询
如果因特殊原因无法使用lastrowid,可以在插入article_fulltext的SQL中嵌入子查询,同时用参数化方式传递标题,避免SQL注入:
mydb = mysql.connector.connect(host="localhost", user="...", password="...", database="knowledgebase") mycursor = mydb.cursor() # 插入article表 sql = "INSERT INTO article (title, author, summary, source) VALUES (%s, %s, %s, %s)" val = (article.title.strip(), ", ".join(article.authors), summary.strip(), url.strip()) mycursor.execute(sql, val) mydb.commit() # 插入article_fulltext表,通过子查询匹配标题获取ID,参数化传递标题 sql = """INSERT INTO article_fulltext (article_ID, body_text, html) VALUES ((SELECT ID FROM article WHERE title = %s), %s, %s)""" val = (article.title.strip(), article.text.strip(), article.html.strip()) mycursor.execute(sql, val) mydb.commit() mydb.close()
注意:方案2依赖标题的唯一性,如果存在重复标题的文章,子查询会返回多个ID,导致插入失败,因此优先推荐方案1。
内容的提问来源于stack exchange,提问作者Max
相关产品推荐
相关产品推荐

