0

我正在尝试插入没有重复的表中。我derbyclient在 Java 中使用 SQL。代码不工作(错误'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++;
}
4

3 回答 3

1

问题是如何构建查询。这不是一个有效的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 = ?);
于 2015-09-22T15:31:45.060 回答
0

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

您必须设置所有这些!

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

于 2015-09-22T15:34:55.733 回答
0

列表后面不能有WHERE子句VALUES

此处查看有效的 DerbyINSERT语句语法。

试试这样的事情(注意使用sysibm.sysdummy1,它保证你最多只插入一条记录。如果你把一个实际的表名放在那里,你可能一次插入多条记录。小心点。):

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,请确保正确设置所有绑定参数。

于 2015-09-22T15:41:52.527 回答