简体   繁体   English

使用外键在表中输入数据时,JDBC异常

[英]JDBC Exception when enter data in the table with foreign keys

When I enter data with my java program (simple dictionary ) it throws an error: 当我使用Java程序(简单字典)输入数据时,将引发错误:

MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails ( singlehaw . card , CONSTRAINT card_ibfk_1 FOREIGN KEY ( wordId ) REFERENCES word ( wordId )) MySQLIntegrityConstraintViolationException:不能添加或更新子行,外键约束失败( singlehawcard ,约束card_ibfk_1外键( wordId )参考wordwordId ))

But when I enter data through query in command prompt I don't face any problem. 但是当我在命令提示符下通过查询输入数据时,我不会遇到任何问题。

here I post my method: 我在这里发布我的方法:

public boolean insert(Card card) {
    Connection connection = MySqlUtils.getInstance().getConnection();
    PreparedStatement statement = null;
    ResultSet resultSet = null;
    int cardId = -1;
    try {
        String INSERT_INTO_TABLE_CARD_QUERY = "INSERT INTO "
                + TBL_CARD + " ("
                + STATUS + ", "
                + RATING + ", "
                + INSERT_TIME + ", "
                + DIC_ID + ", "
                + WORD_ID
                + ") VALUES (?,?,NOW(),?,?)";
        statement = connection.prepareStatement(INSERT_INTO_TABLE_WORDS_QUERY, Statement.RETURN_GENERATED_KEYS);
        statement.setString(1, card.getStatus().name());
        statement.setInt(2, card.getRating());
        statement.setInt(3, card.getDictionaryId());
        statement.setInt(4, card.getWordId());
        statement.execute();

        // get last inserted id
        resultSet = statement.getGeneratedKeys();
        if (resultSet.next())
            cardId = resultSet.getInt(1);
    } catch (SQLException e) {
        e.printStackTrace();
        return false;
    } finally {
        try {
            if (connection != null)
                connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    card.setCardId(cardId);
    return true;
}

and also scripts of creating tables: 以及创建表的脚本:

CREATE TABLE dictionary (
dictionaryId SERIAL,
dictionary VARCHAR(128) NOT NULL,
PRIMARY KEY (dictionaryId)
) ENGINE=INNODB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

CREATE TABLE word (
wordId SERIAL,
word VARCHAR(255) NOT NULL UNIQUE, 
transcription VARCHAR(255),
PRIMARY KEY (wordId)
) ENGINE=INNODB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

CREATE TABLE card (
cardId SERIAL,
status ENUM ('EDIT', 'POSTPONED', 'TO_LEARN', 'LEARNT') NOT NULL DEFAULT 'TO_LEARN',
rating TINYINT DEFAULT '0' NOT NULL,
insert_time TIMESTAMP DEFAULT NOW(),
update_time TIMESTAMP,
dictionaryId BIGINT UNSIGNED NOT NULL,
wordId BIGINT UNSIGNED NOT NULL,
PRIMARY KEY (cardId),
FOREIGN KEY (wordId) REFERENCES word (wordId),
FOREIGN KEY (dictionaryId) REFERENCES dictionary (dictionaryId) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=INNODB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

Perhaps, the fact your wordID fields on the tables have different data types is affecting your program. 也许,表上的wordID字段具有不同的数据类型这一事实正在影响您的程序。 SERIAL is an alias for Bigint. SERIAL是Bigint的别名。 Idea discarded. 想法被丢弃。

Print somwehere in the logs the actual statement being executed. 在日志中打印实际执行的语句。 Maybe there's something that's not being included. 也许有些东西没有包含在内。

Thnx guys a lot. Thnx的家伙很多。 Understood many things from this topic. 了解了本主题中的许多内容。 Right now the problem has gone. 现在问题已经解决了。 The problem was due to populating tables via JUnit tests and because of maven my tests gone in a wrong order so it was difficult to recognize the real problem. 问题是由于通过JUnit测试填充表,并且由于行家我的测试以错误的顺序进行,因此很难识别真正的问题。

You can switch off your constraints ,execute your query, and switch constraints on. 您可以关闭约束,执行查询并打开约束。

SET FOREIGN_KEY_CHECKS=0;
... here is your sql ...
SET FOREIGN_KEY_CHECKS=1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 jdbc 的表中包含两个外键? - How to include two foreign keys in a table in jdbc? 使用Spring JDBC将数据插入到外表中 - Insert data into foreign table using Spring JDBC 使用JDBC获取与一个表相对应的所有外键以及保存这些外键的表 - Getting all foreign keys corresponding to a table and the tables that hold those foreign keys with JDBC 使用来自同一表的两个外键时,beancreation异常引发 - beancreation exception throws when use two foreign keys from the same table 带有3个外键的休眠表 - hibernate table with 3 foreign keys 通过JDBC将长度可变的外键列表作为参数传递给存储过程,然后使用列表将行插入表中 - Pass in variable length lists of foreign keys as arguments to a stored procedure via JDBC and then use the lists to insert rows into a table 当有复合键时,如何使用 jdbc 插入表 - how to insert into table using jdbc, when there are compound keys 使用JDBC获取所有外键 - Get all foreign keys using JDBC 无论如何,是否要使用来自2个不同表的2个不同外键将数据插入表中? - Is there anyway to insert data to table with 2 different foreign keys from 2 different tables? 使用休眠模式从具有两个外键的表中检索数据 - Retrieve data from a table with two foreign keys using hibernate
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM