简体   繁体   中英

python to mysql insert error

I'm trying to insert data into a database hosted on Network Solutions using python and the code below. I was able to successfully connect to the db but when I tried to insert the data into the table I get this error:

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()

This is a picture of the table structure for reference. 表结构

I was wondering what I can do to solve this problem and successfully insert the data into the table. Thanks so much for your help in advance!

The meaning of the error message is that the database structure defines a relationship between the table into which you are inserting data and another table called practice_tests . Values in your practise_test_id1 column are therefore required to exist as primary key values in the practice_tests table to maintain the "relational integrity" of the structure.

You should find that if you insert an appropriate row into practice_tests your code will work - but don't forget to call the connection's commit method otherwise your changes won't be made permanent.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM