【问题标题】:Setting schema in PostgreSQL JDBC doesn't seem to work在 PostgreSQL JDBC 中设置模式似乎不起作用
【发布时间】:2018-10-28 11:54:49
【问题描述】:

我使用表“user”创建了模式“customer1”,并尝试使用 Connection.setSchema() 从 JDBC 连接它:

String url = "jdbc:postgresql://localhost/project";
Properties props = new Properties();
props.setProperty("user", "postgres");
props.setProperty("password", "postgres");

try (Connection conn = DriverManager.getConnection(url, props)) {
    conn.setSchema("customer1");

    try (Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SHOW search_path")) {
        rs.next();
        System.out.println("search_path: " + rs.getString(1));
    }

    try (Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT name FROM user LIMIT 1")) {
        if (rs.next()) {
            System.out.println("user name: " + rs.getString("name"));
        }
    }
}

此代码打印:

search_path: customer1

然后它会抛出带有消息的 PSQLException:

ERROR: column "name" does not exist

如果我在 SELECT 查询中限定“用户”表:

try (Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT name FROM customer1.user LIMIT 1")) {
    if (rs.next()) {
        System.out.println("user name: " + rs.getString("name"));
    }
}

然后打印:

search_path: customer1
user name: name1

并且没有发生错误。我正在使用 JDBC 驱动程序 42.2.2 和 PostgreSQL 服务器 10.4。为什么设置架构不起作用?

【问题讨论】:

    标签: java postgresql jdbc schema


    【解决方案1】:

    userbuilt-in function(和关键字)。所以你不能真正将它用作表名:

    psql (10.4)
    Type "help" for help.
    
    postgres=# select user;
       user
    ----------
     postgres
    (1 row)
    
    postgres=# select * from user;
       user
    ----------
     postgres
    (1 row)
    

    因为它是一个函数,所以它没有列name

    postgres=# select name from user;
    ERROR:  column "name" does not exist
    LINE 1: select name from user;
                   ^
    postgres=#
    

    如果您限定了表格,那么很明显您引用的不是函数,而是表格。

    您可以始终使用架构限定表名,或使用double quotes:select name from "user"; 或简单地查找不与内置函数冲突的表名。

    【讨论】:

      猜你喜欢
      • 2014-08-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-19
      • 2019-06-19
      • 2021-11-07
      • 2014-01-13
      相关资源
      最近更新 更多