Olivier Grégoire Olivier Grégoire - 5 months ago 29
Java Question

How to truncate a Postgresql's table from JDBC

I have a Postgresql database and I want to truncate some tables using JDBC. How do I do that?

This is what I tried, but none worked... without even any error being reported:

Using

CallableStatement
.

try (Connection connection = getConnection();
CallableStatement statement = connection.prepareCall("TRUNCATE " + tableName)) {
return statement.execute();
}


Using
Statement
.

try (Connection connection = getConnection();
Statement statement = connection.createStatement()) {
return statement.execute("TRUNCATE " + tableName);
}


Using
PreparedStatement
.

try (Connection connection = getConnection();
PreparedStatement statement = connection.prepareStatement("TRUNCATE " + tableName)) {
return statement.execute();
}

Answer

After the truncate, I need to commit:

try (Connection connection = getConnection();
     Statement statement = connection.createStatement()) {
  int result = statement.executeUpdate("TRUNCATE " + tableName);
  connection.commit();
  return result;
}

From the documentation:

TRUNCATE is transaction-safe with respect to the data in the tables: the truncation will be safely rolled back if the surrounding transaction does not commit.

Comments