2014-02-25 44 views
1

我有一个Postgresql数据库,我想用JDBC截断一些表。我怎么做?如何从JDBC中截断Postgresql的表

这是我尝试过,但没有工作......没有被报告甚至没有任何错误:

使用CallableStatement

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

使用Statement。使用PreparedStatement

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

'CallableStatement'用于调用DB中的存储过程。 'TRUNCATE'不是SP,因此它不应该工作。当你使用普通的'Statement'时,你会得到什么错误?您还可以启用“JDBC驱动程序”跟踪来检查里面发生了什么。 –

+0

从未报告过任何错误。对于任何尝试。我如何启用JDBC跟踪? –

+0

看起来您的错误在客户端代码的某个地方变得糟糕。在最后加上一个catch(Exception e){e.printStacktrace();}'块。您可以通过遵循'DriverManager.setLogWriter()'API启用跟踪或参考实际的驱动程序指南。您正在使用什么JDBC驱动程序 –

回答

8

的截断后,我需要提交:

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

the documentation

TRUNCATE是交易安全相对于表中的数据:截断会如果周围的事务没有提交,则安全地回滚。

+0

不应该是''TRUNCATE TABLE“+ tableName'? – Marteng

+1

@Marteng [不,根据文档](https://www.postgresql.org/docs/9.1/static/sql-truncate.html) –

1

如果表具有依赖性,则可能会遇到问题。如果是这样,首先截断父表,并使用CASCADE选项。

Connection connection = getConnection(); 
try { 
    PreparedStatement statement = connection.prepareStatement("TRUNCATE " + parentTable1, parentTable2, ... + " CASCADE"); 
    try { 
     return statement.execute(); 
    } finally { 
     statement.close(); 
    } 
} finally { 
    connection.close(); 
}