插入外键约束

时间:2019-04-27 17:32:51

标签: java sql jdbc

我试图将[ORDERID](外键),[PHONENUMBER](外键),[ORDERTIME]和[TOTALPRICE]插入我的订单数据库。 [ORDERID]和[PHONENUMBER]也是我的另外两个集合Customers和OrderedItems的主键。因此,我确保在更新订单表之前先更新那些表。但是,我的订单数据库中仍然出现外键错误。

      try
      {
         // create a PreparedStatement to insert a new address book entry
        PreparedStatement addCustomer
            = connection.prepareStatement("INSERT INTO customers "
            + "(Phonenumber, firstname, lastname, email) \n"
            + " ( SELECT ?, ?, ?, ? \n"
            + "From customers \n"
            + " WHERE phonenumber = ?"
            + " HAVING count(*)=0 )"
            );

         // specify the PreparedStatement's arguments
         addCustomer.setString(1, getFirstName());
         addCustomer.setString(2, getLastName());
         addCustomer.setString(3, getPhone());
         addCustomer.setString(4, getEmail());
         addCustomer.setString(5, getPhone());

         addCustomer.executeUpdate(); // insert the entry

         // create a PreparedStatement to insert a new address book entry
         PreparedStatement addOrderedItems = 
            connection.prepareStatement("INSERT INTO ORDEREDITEMS " +
               "(ORDERID, PIZZAID, PIZZAQN, SIDESID, SIDESQN, DRINKID, DRINKQN)" +
               " VALUES (?, ?, ?, ?, ?, ?, ?)");

         // specify the PreparedStatement's arguments
         addOrderedItems.setInt(1, getID());
         addOrderedItems.setInt(2, getPizza());
         addOrderedItems.setInt(3, getPizzaQuantity());
         addOrderedItems.setInt(4, getSides());
         addOrderedItems.setInt(5, getSidesQuantity());
         addOrderedItems.setInt(6, getDrinks());
         addOrderedItems.setInt(7, getDrinksQuantity());

         addOrderedItems.executeUpdate(); // insert the entry


         // create a PreparedStatement to insert a new address book entry
         PreparedStatement addEntry = 
            connection.prepareStatement("INSERT INTO ORDERS " +
               "(ORDERID, PHONENUMBER, ORDERTIME, TOTALPRICE)" +
               " VALUES (?, ?, ?, ?)");

         // specify the PreparedStatement's arguments
         addEntry.setInt(1, getID());
         addEntry.setString(2, getPhone());
         addEntry.setString(3, getTime());
         addEntry.setDouble(4, getPrice());

         addEntry.executeUpdate(); // insert the entry
         return "index"; // go back to index.xhtml page

0 个答案:

没有答案