Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
260 views
in Technique[技术] by (71.8m points)

prepared statement - Get RETURNING value from Postgresql via Java

From Java, I'm calling a prepared statement in Postgresql with an insert that has a RETURNING clause for my identity column. In PG admin it comes right back, but not sure how to get it from my prepared statement:

        String insertStatement = "INSERT INTO person(
" +
                "            name, address, phone, customer_type, 
" +
                "            start_dtm)
" +
                "    VALUES (?, ?, ?, ?, 
" +
                "            ?)
" +
                "    RETURNING person_id;";


        PreparedStatement stmt = connection.prepareStatement(insertStatement);

        stmt.setObject(1, perToSave.getName(null));
        stmt.setObject(2, editToSave.getAddress());
        stmt.setObject(3, editToSave.getPhone());
        stmt.setObject(4, editToSave.getCustType());
        long epochTime = java.lang.System.currentTimeMillis();
        stmt.setObject(5, new java.sql.Date(epochTime));

        stmt.executeUpdate();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I do not have enough reputation to Comment and my Edit got rejected, so sorry for re-posting the already accepted answer from hd1.

executeUpdate expects no returns; use execute. Check if there is some results before trying to retrieve the value.

String insertStatement = "INSERT INTO person(
" +
                "            name, address, phone, customer_type, 
" +
                "            start_dtm)
" +
                "    VALUES (?, ?, ?, ?, 
" +
                "            ?)
" +
                "    RETURNING person_id;";

PreparedStatement stmt = connection.prepareStatement(insertStatement);

stmt.setObject(1, perToSave.getName(null));
stmt.setObject(2, editToSave.getAddress());
stmt.setObject(3, editToSave.getPhone());
stmt.setObject(4, editToSave.getCustType());
long epochTime = java.lang.System.currentTimeMillis();
stmt.setObject(5, new java.sql.Date(epochTime));

stmt.execute();
ResultSet last_updated_person = stmt.getResultSet();
if(last_updated_person.next()) {
   int last_updated_person_id = last_updated_person.getInt(1);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...