【问题标题】:Postgres JDBC driver not returning error line number as shown in PGAdminPostgres JDBC 驱动程序未返回错误行号,如 PGAdmin 中所示
【发布时间】:2021-06-21 08:02:27
【问题描述】:

Postgres JDBC 驱动程序未返回 PGAdmin 中显示的确切错误行号。当我运行以下程序时:

import java.sql.*;

public class Test {

  public static void main(String[] args) {

    String query = "SELECT table_name, table_type\n" +
      "  FROM information_schema.tabls\n" +
      " WHERE table_schema='public'\n" +
      "   AND table_type in ('BASE TABLE','VIEW') ORDER BY table_type, table_name;";

    try (Connection connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/postgres", "postgres", "postgres")) {

      System.out.println("Connected to PostgreSQL database!");
      Statement statement = connection.createStatement();
      ResultSet resultSet = statement.executeQuery(query);
      while (resultSet.next()) {
        System.out.printf("%-30.30s  %-30.30s%n", resultSet.getString("table_name"), resultSet.getString("table_type"));
      }

    } catch (SQLException e) {
      e.printStackTrace();
    }
  }
}

我收到以下错误:

 org.postgresql.util.PSQLException: ERROR: relation "information_schema.tabls" does not exist
  Position: 38

但是当我在 pgadmin4 上运行相同的查询时,我收到以下错误:

    ERROR:  relation "information_schema.tabls" does not exist
LINE 2:   FROM information_schema.tabls
               ^
SQL state: 42P01
Character: 38

我也想要java程序中的行号。我怎样才能得到它?

【问题讨论】:

  • 你得到了查询中的位置,你需要在你的Java程序中自己计算行号

标签: java postgresql jdbc pgadmin-4


【解决方案1】:

PGAdmin4 是一个使用 Python 驱动程序 psycopg2 的 node.js 后端。该驱动程序只不过是 PostgreSQL 团队创建的名为 libpq 的 C 驱动程序的包装器。

JDBC 驱动程序与数据库通信并使用从服务器接收到的响应。 org.postgresql.core.v3.QueryExecutorImpl#receiveNoticeResponse 负责解析服务器错误的私有方法,它只是创建新的 org.postgresql.util.ServerErrorMessage 实例。因此,服务器给出的响应等于 JDBC 驱动程序显示的响应。

但是对于libpq,从服务器接收到的消息和在客户端显示的消息是不一样的。 libpq 源中有 reportErrorPosition 方法,正好用于添加行信息。这是 PostgreSQL 13.3 的 reference for reportErrorPosition sources。这是place where LINE: x is added给客户端的错误。

总结

使用JDBC驱动需要自己计算行号。或者使用 C 库来为你做这件事。

【讨论】:

    猜你喜欢
    • 2014-08-29
    • 1970-01-01
    • 2021-01-10
    • 2013-08-27
    • 2014-10-24
    • 1970-01-01
    • 2014-07-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多