在PostgreSQL JDBC中设置模式似乎不起作用

时间:2018-05-18 05:50:14

标签: java postgresql jdbc schema

我用表“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查询中限定“user”表:

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。为什么设置架构不起作用?

1 个答案:

答案 0 :(得分:3)

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 quotesselect name from "user";或只是找到不与内置函数冲突的表名。