简体   繁体   中英

PostgreSQL Insertion in JAVA via JSP Incrementing Primary Key

I am writing a JSP application where the user enters a food item and it is entered in a PostgreSQL database. I had no problems implementing this when the user manually had to enter the next primary key, but I removed this ability so that the primary key would be automatically assigned when the enter button is clicked. I would like the query to fetch the current maximum FID (Food ID) and set the new food item's FID to the previous + 1.

try {

    conn = ConnectionProvider.getCon();
    String sql = "select fid from project.food order by fid desc limit 1";
    pst = conn.prepareStatement(sql, ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
    status = pst.getResultSetType();
    f.setFood_id(status + 1);

    pst = conn.prepareStatement("insert into project.food values(?,?,?,?,?,?)");
    pst.setInt(1, f.getFood_id());
    pst.setString(2, f.getFood_name()); //set name
    pst.setInt(3, f.getCount()); //set count
    pst.setInt(4, f.getPrice_per_item()); //set price
    pst.setInt(5, f.getThreshold()); //set threshold
    pst.setString(6, "false");
    status = pst.executeUpdate();
    conn.close();
    pst.close();
} catch (Exception ex) {
    System.out.println(ex);
}
return status;
}

The first food item is successfully inserted into the database in row 1006, instead of the 7th row, which is the first available in the database. Additionally, the second insert fails due to the failure of the primary key to the incremented by 1. The program again tries to insert the next tuple in the same row and thus violates the primary key constraint.

    org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "food_pkey"
    Detail: Key (fid)=(1006) already exists.

Make your primary key autoincrement in the database by declaring it SERIAL datatype (basically an auto incrementing INT ) so a sequence is created to automatically assign values to it.

Then convert your update statement to specify all columns except for the primary key (ie insert into project.food(foo, bar, baz) values (?, ?, ?) , and remove one ? placeholder and the pst.setInt(1,f.getFood_id()); line. This will insert values to all the other columns, and the primary key will be generated by the database.

This way you don't need to do a select when you want to insert (which was a really bad idea anyway), and you let the database do what it does best. You don't need to care about the value of the primary key after that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM