加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

如何从JDBC截断Postgresql的表

发布时间:2020-12-15 05:02:52 所属栏目:Java 来源:网络整理
导读:我有一个 Postgresql数据库,我想使用JDBC截断一些表.我怎么做? 这是我尝试过的,但没有一个工作……甚至没有报告任何错误: 使用CallableStatement. try (Connection connection = getConnection(); CallableStatement statement = connection.prepareCall("
我有一个 Postgresql数据库,我想使用JDBC截断一些表.我怎么做?

这是我尝试过的,但没有一个工作……甚至没有报告任何错误:

使用CallableStatement.

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

使用Statement.

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

使用PreparedStatement.

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

解决方法

截断后,我需要提交:

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

从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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读