我正在尝试插入没有重复的表。我在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++;
}
答案 0 :(得分:1)
问题是如何构建查询。这不是有效的INSERT
syntaxis
首先在您的数据库中尝试这样的,使用虚拟值。
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 = ?);
答案 1 :(得分:0)
您的陈述中至少有8个问号。
你必须设置所有这些!
之后,您可以再次检查并查看是否还有其他错误。
答案 2 :(得分:0)
在WHERE
列表后,您不能拥有VALUES
子句。
查看here有效的Derby INSERT
语句语法。
尝试这样的事情(注意使用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
所述,请确保正确设置所有绑定参数。