我使用表“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。为什么设置架构不起作用?
user
是一个内置函数(和一个关键字)。所以你不能真正使用它作为表名:
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=#
如果您限定了表,那么很明显您引用的不是函数,而是表。
您可以始终使用模式限定表名,或者使用双引号:
select name from "user";
,或者只是找到一个不与内置函数冲突的表名。
https://stackoverflow.com/a/77816297/16827925
2024 年更新
如果要设置架构,请使用
?options=-c%20search_path=
完整网址
jdbc:postgresql://localhost:5432/postgres?options=-c%20search_path=test,public,pg_catalog
根据 postgresql JDBC 文档 https://jdbc.postgresql.org/documentation/use/