I want to use JDBC for preparedStatement
in Java for inserting data into a PostgreSQL database. I have the following DDL
CREATE SEQUENCE serial_no;
CREATE TABLE distributors (
did DECIMAL(3) DEFAULT NEXTVAL('serial_no'),
dname VARCHAR(40) DEFAULT 'lusofilms'
);
I want to insert data into this table. Should the PreparedStatement be
INSERT INTO distributors (did,dname) VALUES (?,?);
And if so how do I do insertions in PreparedStatements
for default values?
2
Answers
Solution 1
use trigger. Reference document: https://www.postgresql.org/docs/current/sql-createtrigger.html
Solution 2
See https://stackoverflow.com/a/21397740/3728901
I have no experience with default values (maybe you must set a java default constant), I normally leave them out of the SQL.
For the rest you can get the generated key as follows:
The try-with-resources syntax – though weird – ensures that
statement
andkeyRS
are both closed (they are AutoCloseable), whatever happens, break/return/exception. You could return inside theif
.Here the update count would be 1.
The result set covers having inserted multiple records, and possible generating more keys per record. You must request this in advance with an extra parameter to
prepareStatement
.