将元组插入数据库

时间:2016-12-05 00:49:32

标签: mysql database jdbc psql

我正在尝试检查是否存在元组。如果是,则返回ID。如果它不存在,则插入它,创建一个新ID,并返回该ID。这就是我所拥有的,但是当我在最后返回productID时,它是0.我也一直收到错误:

  

org.postgresql.util.PSQLException:错误:语法错误在“7”或附近位置:360

任何人都可以帮我理解我在哪里错了吗?提前致谢

public int addProduct(String name, String manufacturer) throws SQLException{ 
        int productId = 0;
        connection.setAutoCommit(false);
        Statement st = null;
        st = this.connection.createStatement();


      try {
        int prod = 0;
        Statement stmt = this.connection.createStatement();
        stmt.execute("SELECT MAX(product_id) FROM Products");
        ResultSet result = stmt.getResultSet();
        if (result.next()) 
          prod = result.getInt(1) + 1;
        System.out.println(prod);       

        st.executeUpdate(              
          "DO                                                                                  " +
          "$do$                                                                                " +
          "BEGIN                                                                               " +
          "IF NOT EXISTS (SELECT 1 FROM Products WHERE                                         " +
          "Products.name = " + name + " AND                                                    " +
          "Products.manufacturer = " + manufacturer + ") THEN                                  " +
          "INSERT INTO Products (product_id, name, category, manufacturer)                     " +
          "VALUES (" + prod + ", " + name + ",                                                 " +
          "" + null + ", " + manufacturer + ");                                                " +
          "END IF;                                                                             " +
          "END;                                                                                " +
          "$do$                                                                                ; " 
        );

        ResultSet rsFind = st.executeQuery(              
          "SELECT Products.product_id FROM Products WHERE                                      " +
          "Products.name = '" + name + "' AND                                                  " +
          "Products.manufacturer = '" + manufacturer + ";                                      "
        );

        if (rsFind.next()) {
          productId = rsFind.getInt("product_id");
          System.out.println(productId);  
        }

      } catch (SQLException e) {
          System.err.println(e);

      } finally {
        if (st != null) st.close();
      }

      this.connection.setAutoCommit(true);
      return productId;
    }

0 个答案:

没有答案