gpt4 book ai didi

JAVA、SQL、插入不重复

转载 作者:行者123 更新时间:2023-12-01 11:08:01 25 4
gpt4 key购买 nike

我正在尝试插入没有重复项的表。我在 Java 中使用 SQL derbyclient。该代码无法正常工作(错误为'where not办法')。有什么想法吗?

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 = ?);

关于JAVA、SQL、插入不重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32720875/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com