Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
}
like image 346
Olivier Grégoire Avatar asked Feb 25 '14 15:02

Olivier Grégoire


People also ask

How do you truncate a table in Java?

stTruncate. executeUpdate("truncate table tblName");

How do I truncate a table in PostgreSQL?

The PostgreSQL TRUNCATE TABLE command is used to delete complete data from an existing table. You can also use DROP TABLE command to delete complete table but it would remove complete table structure from the database and you would need to re-create this table once again if you wish to store some data.

How do I truncate all data in a table?

To remove all data from an existing table, use the SQL TRUNCATE TABLE order. You can also use the DROP TABLE command to delete an entire table. But Truncate will remove the entire table structure from the database, and you will need to recreate the table if you want to store any data.


2 Answers

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.

like image 152
Olivier Grégoire Avatar answered Oct 06 '22 03:10

Olivier Grégoire


You may run into issues if the table has dependencies. If so, truncate the parent tables first, and also use the CASCADE option.

Connection connection = getConnection();
try {
    PreparedStatement statement  = connection.prepareStatement("TRUNCATE " + parentTable1, parentTable2, ... + " CASCADE");
    try {
        return statement.execute();
    } finally {
        statement.close();
    }
} finally {
    connection.close();
}
like image 21
John Hogan Avatar answered Oct 06 '22 05:10

John Hogan