コード例 #1
0
  /*
   * addAuto method. parse the Automobile object and add them to three tables.
   */
  public void addAuto(Automobile auto) {
    String name = null;
    float price = 0;
    int autoid = 0;
    String sql = null;
    try {
      String autoName = auto.getMake() + " " + auto.getModel();
      price = auto.getBasePrice();
      sql =
          "insert into automobile (name, base_price) values('"
              + autoName
              + "',"
              + price
              + ")"; // MySQL command
      statement.executeUpdate(sql); // add to automobile table

      sql = "select id from automobile where name ='" + autoName + "';";
      ResultSet rs = statement.executeQuery(sql); // use ResultSet object to receive
      while (rs.next()) {
        autoid = rs.getInt("id"); // get auto_id
      }
      for (int i = 0; i < auto.getOptionSetNum(); i++) {
        name = auto.getOptionSetName(i);
        sql = "insert into optionset (name, auto_id) values('" + name + "'," + autoid + ")";
        statement.executeUpdate(sql); // add to optionset table
        int opsid = 0;
        sql = "select id from optionset where name ='" + name + "';";
        ResultSet rrs = statement.executeQuery(sql);
        while (rrs.next()) {
          opsid = rrs.getInt("id"); // get optionset id
        }
        for (int j = 0; j < auto.getOptionNum(i); j++) {
          name = auto.getOptionName(i, j);
          price = auto.getOptionPrice(i, j);
          sql =
              "insert into options (name, price, option_id) values('"
                  + name
                  + "',"
                  + price
                  + ","
                  + opsid
                  + ")";
          statement.executeUpdate(sql); // add to options table
        }
      }

    } catch (SQLException e) {
      e.printStackTrace();
    }
  }