我想将用户选择的产品插入称为cart的表中,该表具有两列:cart_id和item_id_FK都是外键。 User_id和id在构造函数中传递,然后插入cart_id和item_id_fk。 代码中未显示任何错误,我再次检查了连接用户名和密码,除cart表外,其他一切正常。 我尝试将try and catch语句放入其中,并重复不起作用的步骤。
if (e.getSource()==AddToCartBtn)
{
//Check to see if item is available
String SizeSelection;
SizeSelection = SizeCmbx.getSelectedItem().toString();
String DBURL ="JDBC:MySql://localhost:3306/shoponline?useSSL=true";
String USER ="root";
String PASSWORD ="12345678";
try {
Connection con = DriverManager.getConnection(DBURL, USER, PASSWORD);
String sql2 = String.format("select itemid,size,productid_fk from items where size='%s' and productid_fk=%d",SizeSelection,id);
PreparedStatement statement = con.prepareStatement(sql2);
ResultSet result = statement.executeQuery(sql2);
String sql3 = "insert into cart (CartID, ItemID_FK)" + " values (?, ?)";
PreparedStatement preparedStmt = con.prepareStatement(sql3);
preparedStmt.setInt(1, user_ID);
preparedStmt.setInt(2, id);
if(result.next())
{
//if item is available
// execute the preparedstatement
preparedStmt.execute();
}//end if
con.close();
}// end try
catch (SQLException ex){
ex.printStackTrace();
}//end catch
答案 0 :(得分:0)
将executeQuery更改为executeUpdate:
executeQuery(sql3)
到
executeUpdate(sql3)
我相信整数不需要在其周围插入'',您也可以尝试删除它们。可能是误以为他们是角色或类似的东西。
否则,如果以上解决方法均无效,请尝试执行以下操作:
String query = "insert into cart (CartID, ItemID_FK)"
+ " values (?, ?)";
// create the mysql insert preparedstatement
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setInt(1, xInt);
preparedStmt.setInt(2, yInt);
// execute the preparedstatement
preparedStmt.execute();
conn.close();