2

当我用我的 java 程序(简单字典)输入数据时,它会抛出一个错误:

MySQLIntegrityConstraintViolationException:无法添加或更新子行:外键约束失败(singlehawcard,CONSTRAINT card_ibfk_1FOREIGN KEY(wordId)REFERENCES wordwordId))

但是当我在命令提示符下通过查询输入数据时,我没有遇到任何问题。

在这里我发布我的方法:

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;
}

以及创建表的脚本:

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;
4

3 回答 3

0

Thnx伙计们很多。从这个话题中了解了很多东西。现在问题已经解决了。问题是由于通过 JUnit 测试填充表,并且由于 Maven 我的测试顺序错误,因此很难识别真正的问题。

于 2013-01-27T00:47:10.347 回答
0

也许,表上的 wordID 字段具有不同的数据类型这一事实正在影响您的程序。SERIAL 是 Bigint 的别名。想法被抛弃。

在日志中打印正在执行的实际语句。也许有些东西没有被包括在内。

于 2013-01-24T17:09:49.147 回答
-1

您可以关闭约束、执行查询并打开约束。

SET FOREIGN_KEY_CHECKS=0;
... here is your sql ...
SET FOREIGN_KEY_CHECKS=1;
于 2013-01-24T15:42:07.100 回答