python到mysql插入错误
我正在尝试使用python和下面的代码将数据插入到网络解决方案上托管的数据库中。我能够成功地连接到数据库,但当我尝试将数据插入表时,出现以下错误:python到mysql插入错误,python,mysql,Python,Mysql,我正在尝试使用python和下面的代码将数据插入到网络解决方案上托管的数据库中。我能够成功地连接到数据库,但当我尝试将数据插入表时,出现以下错误: 1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`focused`.`test_results`, CONSTRAINT `test_results_practice_tests_FK` FOREIGN KEY (`practice_tes
1452 (23000): Cannot add or update a child row: a foreign key constraint fails (`focused`.`test_results`, CONSTRAINT `test_results_practice_tests_FK` FOREIGN KEY (`practice_test_id1`) REFERENCES `practice_tests` (`practice_test_id`))
import mysql.connector
from mysql.connector import errorcode
config = {
'user': '{user}',
'password': '{psswd}',
'host': '{host}',
'database': '{dbname}',
'raise_on_warnings': True,
}
try:
cnx = mysql.connector.connect(**config)
cursor = cnx.cursor()
query = """INSERT INTO test_results (result_id, student_id1, practice_test_id1, section_1_score, section_1_missed, section_2_score, section_2_missed, section_3_score, section_3_missed, section_4_score, section_4_missed, e_reading_score, e_analysis_score, e_writing_score, command_score, command_missed, words_score, words_missed, expression_score, expression_missed, heart_score, heart_missed, standard_score, standard_missed, problem_score, problem_missed, passport_score, passport_missed, history_score, history_missed, science_score, science_missed, math_score, reading_score) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)"""
data_test_result = (1, 1, 1, 1, '', 1, '', 1, '', 1, '', 1, 1, 1, 1, '', 1, '', 1, '', 1, '', 1, '', 1, '', 1, '', 1, '', 1, '', 1, 1)
cursor.execute(query, data_test_result)
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Something is wrong with your user name or password")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("Database does not exist")
else:
print(err)
else:
cnx.close()
这是一张表格结构图,供参考。
我想知道我能做些什么来解决这个问题并成功地将数据插入表中。非常感谢您的帮助 错误消息的含义是,数据库结构定义了插入数据的表与另一个名为
practice\u tests
的表之间的关系。因此,practice\u test\u id1
列中的值必须作为主键值存在于practice\u tests
表中,以保持结构的“关系完整性”
您应该发现,如果在
practice\u tests
中插入适当的行,您的代码将正常工作,但是不要忘记调用连接的commit
方法,否则您的更改将不会永久化 错误消息的含义是,数据库结构定义了插入数据的表与另一个名为practice\u tests
的表之间的关系。因此,practice\u test\u id1
列中的值必须作为主键值存在于practice\u tests
表中,以保持结构的“关系完整性”
您应该发现,如果在practice\u tests
中插入适当的行,您的代码将正常工作,但是不要忘记调用连接的commit
方法,否则您的更改将不会永久化