0
I’m having the following problem, I want to enter the data from my expense table but some error happens with my Foreign key, which may be ?
background: Cannot add or update a Child Row: a Foreign key Constraint fails (
trabalhoviagemd
.despesa
, CONSTRAINTdespesa_ibfk_1
FOREIGN KEY (idViagem
) REFERENCESviagem
(idViagem
))
Insert method from Dao
public class DespesaDao {
private final static String DATE_FORMAT = "yyyy-MM-dd";
private static final int QTDE = 10; // Constante = quantidade de endereços;
private static DespesaBean vetor[] = new DespesaBean[QTDE];
private static final String cabecalho = "idViagem,tipoDespesa, valorDespesa, dataDespesa\n";
public static boolean inserir(DespesaBean despesa) {
boolean executou = false;
if (ConexaoMySQL.conectar()) {
try {
Connection con = ConexaoMySQL.getConexao();
String sql = "Insert into despesa values (0,?,?,?,?)";
PreparedStatement P = con.prepareStatement(sql);
P.setInt(1, despesa.getIdViagem());
P.setString(2, despesa.getTipoDespesa());
P.setDouble(3, despesa.getValorDespesa());
P.setString(4,DataHelper.CalendarToString(DATE_FORMAT,despesa.getDataDespesa()));
P.executeUpdate();
System.out.println("despesaDao.inserir:\n" + P);
P.close();
executou = true;
} catch (Exception e) {
System.out.println("despesaDao: " + e.getMessage());
e.printStackTrace();
} finally {
ConexaoMySQL.fecharConexao();
}
}
return executou;
}
Tables Do banco
CREATE TABLE viagem (
idViagem INT NOT NULL AUTO_INCREMENT,
tipoViagem VARCHAR(16) NOT NULL,
dataInicio DATE NOT NULL,
dataEncerramento DATE NOT NULL,
cidade VARCHAR(16) NOT NULL,
uf VARCHAR(16) NOT NULL,
valorDiaria DOUBLE NOT NULL,
colaborador VARCHAR(32) NOT NULL,
cliente VARCHAR(32) NOT NULL,
PRIMARY KEY (`idViagem`));
select * from viagem;
CREATE TABLE despesa (
idDespesa INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
idViagem INT NOT NULL,
tipoDespesa VARCHAR(16) NOT NULL,
valorDespesa DOUBLE NOT NULL,
dataDespesa DATE NOT NULL,
FOREIGN KEY (idViagem) REFERENCES trabalhoviagemd.viagem(idViagem));
Our guy sorry to have to make you write this complete answer for such a simple mistake, is that in my main I forgot to set the idViagem or I had no input for the user to enter with the travel id number, if I could give you 100+ reward points, but thank you so much for your support guy helped a lot in understanding ;-)
– Marcelo T. Cortes
hahahaha imagines! I’m a bit of a detail person! I didn’t know your level of knowledge to leave only the text kkk Hug
– Felipe Douradinho
Thanks guy hug!
– Marcelo T. Cortes