Flup
Flup

Reputation: 45

Postgres INSERT INTO where clause with Java preparedstatement

I am trying to insert data in a table with a PreparedStatement in Java and postgres JDBC. I want to insert into column startdate and column enddate values with a condition that roomnumber is given (?);

PreparedStatement stm = conn.prepareStatement( "INSERT INTO room(startdate,enddate) values(?,?) WHERE roomnumber = ?"))

It gives me an error at WHERE. What is the correct syntax. Many thanks

Upvotes: 2

Views: 9593

Answers (3)

Robert
Robert

Reputation: 1

Use Insert Into Select and Not Insert Into Values

INSERT INTO table1(firstname, lastname)
    select 'Sally', 'Brown'
    Where exists (Select 1 from table2 where field1=val1 )

Upvotes: 0

rsa
rsa

Reputation: 339

You can use something like that:

insert into room(startdate, enddate) select '2020-01-01'::date, '2020-02-11'::date where (select roomnumber = ? from roomnumber_table);

Also check out this: https://www.postgresql.org/docs/12/queries-with.html

Upvotes: 0

mhvelplund
mhvelplund

Reputation: 2341

Use UPDATE to change existing rows, INSERT to create new rows. There are a number of examples in the documentation: https://www.postgresql.org/docs/9.5/static/sql-update.html

E.g.: UPDATE room SET startdate = ?, enddate = ? WHERE roomnumber = ?

Upvotes: 5

Related Questions