4

I have trouble inserting data into my table. I don't know what is the database model or schema looks like cause i am just finding and fixing error on the existing program until i encounter this error

MySql.Data.MySqlClient.MySqlException (0x80004005): Cannot add or update a child row: a foreign key constraint fails (`my_database`.`movies_class`, CONSTRAINT `fk_movies_class_movies1` FOREIGN KEY (`movie_id`) REFERENCES `movies_notworking` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION)

at MySql.Data.MySqlClient.MySqlStream.ReadPacket()

at MySql.Data.MySqlClient.NativeDriver.GetResult(Int32& affectedRow, Int64& insertedId)

at MySql.Data.MySqlClient.Driver.GetResult(Int32 statementId, Int32& affectedRows, Int64& insertedId)

at MySql.Data.MySqlClient.Driver.NextResult(Int32 statementId, Boolean force)

at MySql.Data.MySqlClient.MySqlDataReader.NextResult()

at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)

at MySql.Data.MySqlClient.MySqlCommand.ExecuteNonQuery()

and here is my code

public void tabinsertcheck(MySqlConnection myconn, DataGridView dgv, int intid)
    {
        for (int i = 0; i < dgv.Rows.Count; i++)
        {
            if (dgv[0, i].Value != null)
            {
                if ((bool)dgv[0, i].Value)
                {
                    StringBuilder sqry = new StringBuilder();
                    sqry.Append("select max(id) from movies_class");
                    MySqlCommand cmd = new MySqlCommand(sqry.ToString(), myconn);
                    int max_id = Convert.ToInt32(cmd.ExecuteScalar())+1;
                    sqry = new StringBuilder();
                    sqry.Append(String.Format("insert into movies_class values({0},{1},{2})",
                        max_id,intid, dgv[3, i].Value.ToString()));

                    if (myconn.State == ConnectionState.Closed)
                        myconn.Open();
                    cmd = new MySqlCommand(sqry.ToString(), myconn);
                    cmd.ExecuteNonQuery();
                    cmd.Dispose();
                    myconn.Close();
                }
            }

        }
    }

I am using loop because i have a lot of checkbox every checkbox it is saving in database, and i don't know how to fix it. Thanks in advance

1 Answer 1

5

You are trying to insert a row into the movies_class table with a value for movie_id field that does not exist in the movies_notworking table Id field. Check your data and make sure that you are inserting right values for the reference fields in the table.

Sign up to request clarification or add additional context in comments.

1 Comment

sorry i can't vote you up, i need 15 rep.. but i accept your answer. thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.