0

如果已经不存在具有主键的记录,我需要添加记录;否则将更新现有记录。为此,我正在使用主键查询数据库。如果不存在记录,我将添加;否则更新。我正在使用原始 JDBC 在 Java 中对此进行编码。

有一个更好的方法吗?

4

4 回答 4

4
  1. 插入……选择……不存在的地方
  2. INSERT INTO ... VALUES ... ON 重复键更新 id = id
  3. 替换成 ... 选择 ... 从 ...
于 2013-09-30T06:27:26.217 回答
2

The most soft way to do this is to use special query INSERT ... ON DUPLICATE KEY UPDATE query in My Sql. It is much more effective than check is conflict exist on the application side.

Code snippet for example:

PreparedStatement statement = null;
try {
    statement = connection.prepareStatement(
        "INSERT INTO table (a,b,c) VALUES (?,?,?) ON DUPLICATE KEY UPDATE c=?;"
    );
    int paramIndex = 1;
    statement.setInt(parameterIndex++, primaryKeyValue);
    statement.setInt(parameterIndex++, secondValue);
    statement.setInt(parameterIndex++, thirdValue);
    statement.setInt(parameterIndex++, thirdValue);
    int updatedCount = statement.executeUpdate();
} finally {
    statement.close();
}
于 2013-09-30T06:11:03.860 回答
0

The simplest and the most general way is to count the record before insert/update.

Pseudo Code:

SELECT COUNT(*) as recordCount FROM mytable WHERE keyField = ?
if (recordCount > 0) {
   UPDATE mytable SET value1=? WHERE keyField = ?
} else {
   INSERT INTO mytable (keyField, value1) VALUES (?, ?)
}
于 2013-09-30T06:34:08.713 回答
0

另一种方法是REPLACE INTO,它采用相同的语法,INSERT但在插入之前主键已经存在时删除旧条目。

于 2013-09-30T06:19:22.713 回答