【问题标题】:SQLException: ERROR: syntax error at or near "\"SQLException: 错误: "\" 处或附近的语法错误
【发布时间】:2018-11-21 05:52:32
【问题描述】:

我想将 ma 数据库中的表列表转换为 String。我已经连接数据库,但是当我尝试使用 Postgres "\dt" 函数时,getTables() 抛出 org.postgresql.util.PSQLException: ERROR: syntax error at or near "\". 问题是什么?一个简单的反斜杠被报告为错误 JDK(将\dt 视为正则表达式)。

import java.sql.*;
import java.util.ArrayList;

public class DataConnect {
    Statement statement = null;
    Connection connection = null;
    DataConnect() {
        try {
            Class.forName("org.postgresql.Driver");
            connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/postgres", "", "");
            statement = connection.createStatement();
        } catch (ClassNotFoundException e) {

            e.printStackTrace();
            System.out.append("Driver is missing");
            end();
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.append("Wrong order");
            end();
        }
    }
    ArrayList<String> getTables() {
        ArrayList tables = new ArrayList();
        try {
            ResultSet rs = statement.executeQuery("\\dt");
            while (rs.next()) {
                String databaseName = rs.getString("Name");
            }
            return tables;
        } catch (Exception e) {
            e.printStackTrace();
            end();
            return null;
        }
    }
}

【问题讨论】:

  • 当然,我删除用户和密码只是为了在堆栈上发布

标签: java sql postgresql psql


【解决方案1】:

\dt 不是有效的 SQL 语法 - 它是 meta-command。您可以通过查询信息架构来执行类似的功能:

ResultSet rs = statement.executeQuery("SELECT table_name FROM information_schema.tables");

【讨论】:

  • psql 文档称他们为 Meta-Commands
  • @Andreas 我觉得“宏”听起来很奇怪,但记不起正确的名字。谢谢!将其编辑到我的答案中。
猜你喜欢
  • 2017-02-20
  • 2017-07-15
  • 2010-12-24
  • 2016-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多