Answer the question
In order to leave comments, you need to log in
Java + JDBC + PostgreSQL - how to correctly update a record if it exists or add if it does not exist?
There is a collection with many objects. The collection is displayed in a table. An offline user can add and delete records, as well as update previously received via SELECY * FROM ...
I want to implement the "Save All" function, in which the program would go through all the collections and update the records in the database, if they exist, and add new ones if they don't exist.
Came to the following solution from the Java side:
@Override
public void updateAll(List<User> users)
{
//online
Connection connection = null;
PreparedStatement statement = null;
try
{
connection = Database.getInstance().getConnection();
connection.setAutoCommit(false);
for (User user : users)
{
statement = connection.prepareStatement(""); //вот тут правильно составить запрос
statement.execute();
}
connection.commit();
}
catch (SQLException ex)
{
Log.error("Unable to updateAll users. " + ex.getMessage());
}
finally
{
Database.closeQuietly(statement);
Database.closeQuietly(connection);
}
}
INSERT INTO the_table (id, column_1, column_2)
VALUES (1, 'A', 'X'), (2, 'B', 'Y'), (3, 'C', 'Z')
ON CONFLICT (id) DO UPDATE
SET column_1 = excluded.column_1,
column_2 = excluded.column_2;
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question