我在将数据插入表格时遇到问题。我不知道数据库模型或模式是什么样的原因我只是在现有程序中找到并修复错误,直到遇到此错误
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()
这是我的代码
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();
}
}
}
}
我正在使用循环,因为我在数据库中保存的每个复选框都有很多复选框,我不知道如何修复它。提前致谢
答案 0 :(得分:5)
您正尝试在movies_class
表格中插入一行,其中movie_id
字段movies_notworking
字段中不存在Id
字段的值。检查您的数据并确保为表中的参考字段插入正确的值。