使用JDBC连接到postgres时是否可以指定架构?

问题描述 投票:121回答:8

可能吗?我可以在连接URL上指定它吗?怎么做?

java database postgresql jdbc database-schema
8个回答
172
投票

我知道这已经得到了回答,但是我遇到了同样的问题,试图指定用于liquibase命令行的模式。

更新从JDBC v9.4开始,您可以使用新的currentSchema参数指定url,如下所示:

jdbc:postgresql://localhost:5432/mydatabase?currentSchema=myschema

出现基于早期补丁:

http://web.archive.org/web/20141025044151/http://postgresql.1045698.n5.nabble.com/Patch-to-allow-setting-schema-search-path-in-the-connectionURL-td2174512.html

哪个提议网址是这样的:

jdbc:postgresql://localhost:5432/mydatabase?searchpath=myschema

56
投票

version 9.4开始,您可以在连接字符串中使用currentSchema参数。

例如:

jdbc:postgresql://localhost:5432/mydatabase?currentSchema=myschema

48
投票

如果在您的环境中可以,您还可以将用户的默认架构设置为所需的架构:

ALTER USER user_name SET search_path to 'schema'

42
投票

我不相信有一种方法可以在连接字符串中指定架构。看来你必须执行

set search_path to 'schema'

在建立连接以指定架构之后。


7
投票

我向PostgreSQL JDBC驱动程序提交了一个补丁的更新版本,以便在几年前启用它。您必须从源代码构建PostreSQL JDBC驱动程序(在添加补丁后)才能使用它:

http://archives.postgresql.org/pgsql-jdbc/2008-07/msg00012.php

http://jdbc.postgresql.org/


6
投票

DataSourcesetCurrentSchema

实例化DataSource实现时,请查找设置当前/默认架构的方法。

例如,在PGSimpleDataSource类上调用setCurrentSchema

org.postgresql.ds.PGSimpleDataSource dataSource = new org.postgresql.ds.PGSimpleDataSource ( );
dataSource.setServerName ( "localhost" );
dataSource.setDatabaseName ( "your_db_here_" );
dataSource.setPortNumber ( 5432 );
dataSource.setUser ( "postgres" );
dataSource.setPassword ( "your_password_here" );
dataSource.setCurrentSchema ( "your_schema_name_here_" );  // <----------

如果未指定,Postgres会尝试连接到名为public的模式。


3
投票

不要忘记你可以在单独的声明中使用的SET SCHEMA 'myschema'

SET SCHEMA'value'是SET search_path TO值的别名。使用此语法只能指定一个模式。

由于JDBC驱动程序上有9.4版本和可能的早期版本,因此支持setSchema(String schemaName)方法。


1
投票

在Go中使用“sql.DB”(注意带有下划线的search_path):

postgres://user:password@host/dbname?sslmode=disable&search_path=schema
© www.soinside.com 2019 - 2024. All rights reserved.