JAVA, SQL, 插入不重复

JAVA, SQL, insert into no-duplicates

我正在尝试不重复地插入 table。我在 Java 中使用 SQL derbyclient。代码不工作(错误 'where not exists')。有什么想法吗?

Connection connection = DriverManager.getConnection("jdbc:derby://localhost:1527/PetroleumDataStorageSystemDB;create=true");
PreparedStatement statement;
int i = 1;
int progress = 0;
for (Refuel refuelList1 : refuelList) {
     progress = (i / refuelList.size()) * 100;
     String sql = "INSERT INTO refuel (id_tank, time, fuel_volume, "
                  + "refueling_speed) VALUES (?,?,?,?) "
                  + "WHERE NOT EXISTS (SELECT * FROM refuel WHERE "
                  + "id_tank = ? AND time = ? AND fuel_volume = ? AND "
                  + "refueling_speed = ?)";
     statement = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
     statement.setInt(1, refuelList1.getTankID());
     statement.setString(2, refuelList1.getTime());
     statement.setDouble(3, refuelList1.getFuelVolume());
     statement.setDouble(4, refuelList1.getRefuelingSpeed());
     statement.execute();
     i++;
}

问题在于您如何构建查询。这不是有效的 INSERT 语法

首先在您的数据库上尝试类似的操作使用虚拟值

INSERT INTO refuel (id_tank, time, fuel_volume, refueling_speed) 
 SELECT ?, ?, ?, ? 
 FROM refuel
 WHERE NOT EXISTS (SELECT 
                   FROM refuel 
                   WHERE
                       id_tank = ? 
                   AND time = ? 
                   AND fuel_volume = ?
                   AND refueling_speed = ?);

你的陈述中至少有8个问号。

你必须全部设置!

之后您可以再次检查,看看是否还有其他错误。

VALUES 列表后不能有 WHERE 子句。

查看 here 以获得有效的 Derby INSERT 语句语法。

试试这样的方法(注意 sysibm.sysdummy1 的使用,它保证您最多只插入一条记录。如果您在其中放置一个实际的 table 名称,您可能可能一次插入多条记录。小心。):

INSERT INTO refuel (id_tank, tank, fuel_volume, refueling_speed)
SELECT ?, ?, ?, ?
  FROM sysibm.sysdummy1
 WHERE NOT EXISTS (SELECT *
                     FROM refuel
                    WHERE id_tank = ?
                      AND time = ?
                      AND fuel_volume = ?
                      AND refueling_speed = ?)

此外,如 Davide Lorenzo MARINO 所述,请确保正确设置所有绑定参数。