Insert or update the table using JDBC

I have some records to import. It’s ok the first time when they are being inserted. If I try to import the same data again I receive a org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint. How can I update the records in the database if the data is the same/or changed and insert if it’s new data using JDBC?

public void store(Object entity) throws Exception {
    try {
        if (this.updateEntity((XEntity) entity) == 0) {
            this.insertEntity((XEntity) entity);
        }

        ...

    } catch (SQLException sqlEx) {
        ...
    }
}

private int updateEntity(XEntity entity) throws SQLException {
    PreparedStatement prepStmt = this.getUpdatePreparedStmt();
    ...
    return prepStmt.executeUpdate();
}

private void insertEntity(XEntity entity) throws SQLException {
    ...
    this.getInsertPreparedStmt().executeUpdate();
}

The problem is fixed now. I’ve provided an answer below.

Hello, buddy!责编内容来自:Hello, buddy! (源链) | 更多关于

阅读提示:酷辣虫无法对本内容的真实性提供任何保证,请自行验证并承担相关的风险与后果!
本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 综合编程 » Insert or update the table using JDBC

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录