我正在尝试检查数据库以查看是否存在给定的名称和制造商。如果他们然后返回产品ID。如果它们不是,则将它们插入数据库,创建一个新的productId并返回它。当我打印product_id的值时,此查询返回0。
public int addProduct(String name, String manufacturer) throws SQLException{
int productId = 0;
Statement st = null;
connection.setAutoCommit(false);
try {
st = this.connection.createStatement();
ResultSet rs = st.executeQuery(
"BEGIN TRAN IF EXISTS (SELECT Products.name, Products.manufacturer FROM Products WITH (updlock, serializable) WHERE (Products.name = name AND Products.manufacturer = manufacturer) BEGIN INSERT INTO Products (product_id, name, category, manufacturer) VALUES (productId, name, null, manufacturer) END IF; COMMIT TRANSACTION;" );
if(rs.next())
productId = rs.getInt("product_id");
else
System.out.println("Product not added!");
} catch (SQLException e) {
System.err.println(e);
} finally {
if (st != null) st.close();
}