0

使用jdbc连接postgresql数据库的一知半解 -利来国际app

张玉龙 2021-11-05
147

在postgresql发行版中只包含两个客户端接口: libpq 和 ecpg

  • libpq is included because it is the primary c language interface, and because many other client interfaces are built on top of it.
  • ecpg is included because it depends on the server-side sql grammar, and is therefore sensitive to changes in postgresql itself.

其他语言客户端接口:

name language comments website
dbd::pg perl perl dbi driver
jdbc java type 4 jdbc driver
libpqxx c c interface
node-postgres javascript node.js driver
npgsql .net .net data provider
pgtcl tcl -
pgtclng tcl -
pq go pure go driver for go’s database/sql
psqlodbc odbc odbc driver
psycopg python db api 2.0-compliant

  java database connectivity (jdbc) 是一种用于执行 sql 语句的 java api , 可以为多种关系数据库提供统一访问 , 它由一组用 java 语言编写的类和接口组成。

  jdbc api 是 sun 公司提出的访问数据库的接口标准,是访问数据库的通用api。

  postgresql jdbc driver 利来国际app官网和 jdbc 驱动下载:
  postgresql jdbc driver 官方文档:

  以下学习了几种jdbc连接postgresql数据库的java代码,依次迭代,推荐方式六。在这里,只学习怎么连接数据库,至于怎么操作数据库就暂时放弃了,毕竟术业有专攻。上次接触java代码还是上大学的时候,已经过去好多年了,所以以下代码肯定还不够严谨,仅供参考学习,主要还是研究jdbc连接postgresql数据库的问题。

方式一,driver 方式连接数据库

import java.sql.connection; import java.sql.driver; import java.sql.sqlexception; import java.util.properties; public class postgresqljdbc { public static void main(string[] args) throws classnotfoundexception, sqlexception { driver driver = new org.postgresql.driver(); string url = "jdbc:postgresql://192.168.58.20:5000/postgres"; properties info = new properties(); info.setproperty("user", "postgres"); info.setproperty("password", "postgres"); connection conn = driver.connect(url, info); system.out.println(conn); } }

方式二,使用反射获取driver实现类对象

  使用反射获取driver实现类对象,不需要使用第三方的api[new org.postgresql.driver()],使程序具有更好的可移植性(更换数据库),对方式一的迭代

import java.sql.connection; import java.sql.driver; import java.util.properties; public class postgresqljdbc { public static void main(string[] args) throws exception { class cs = class.forname("org.postgresql.driver"); driver driver = (driver) cs.newinstance(); string url = "jdbc:postgresql://192.168.58.20:5000/postgres"; properties info = new properties(); info.setproperty("user", "postgres"); info.setproperty("password", "postgres"); connection conn = driver.connect(url, info); system.out.println(conn); } }

方式三,使用 drivermanager 替换 driver,对方式二的迭代

import java.sql.connection; import java.sql.driver; import java.sql.drivermanager; import java.util.properties; public class postgresqljdbc { public static void main(string[] args) throws exception { class cs = class.forname("org.postgresql.driver"); driver driver = (driver) cs.newinstance(); string url = "jdbc:postgresql://192.168.58.20:5000/postgres"; string username = "postgres"; string password = "postgres"; drivermanager.registerdriver(driver); connection conn = drivermanager.getconnection(url, username, password); system.out.println(conn); } }

方式四,对方式三的优化

  只加载(class.forname)驱动,不用显式的注册(registerdriver)驱动,jdbc driver类中写了注册,加载org.postgresql.driver自动就注册了。

import java.sql.connection; import java.sql.driver; import java.sql.drivermanager; import java.util.properties; public class postgresqljdbc { public static void main(string[] args) throws exception { string url = "jdbc:postgresql://192.168.58.20:5000/postgres"; string username = "postgres"; string password = "postgres"; class.forname("org.postgresql.driver"); connection conn = drivermanager.getconnection(url, username, password); system.out.println(conn); } }

方式五,加载(class.forname)驱动 也可以省略

  加载(class.forname)驱动 也可以省略,因为驱动包 postgresql-42.2.20.jar\meta-inf\services\java.sql.driver 文件中有 org.postgresql.driver,但是建议使用,因为不是所有的驱动包都有这个配置。

import java.sql.connection; import java.sql.driver; import java.sql.drivermanager; import java.util.properties; public class postgresqljdbc { public static void main(string[] args) throws exception { string url = "jdbc:postgresql://192.168.58.20:5000/postgres"; string username = "postgres"; string password = "postgres"; //class.forname("org.postgresql.driver"); connection conn = drivermanager.getconnection(url, username, password); system.out.println(conn); } }

方式六,最终且推荐版,将数据库连接需要的基本信息放到配置文件中,通过读取配置文件获取连接

  好处:1. 数据和代码分离 2. 如果修改配置文件信息,可以避免对程序重新打包

[root@pgtest3 ~]# vi postgresqljdbc.java import java.io.inputstream; import java.sql.connection; import java.sql.drivermanager; import java.sql.preparedstatement; import java.sql.resultset; import java.util.properties; public class postgresqljdbc { public static void main(string[] args) throws exception { // 读取配置文件信息 inputstream conf = postgresqljdbc.class.getclassloader().getresourceasstream("jdbc.properties"); properties pros = new properties(); pros.load(conf); string url = pros.getproperty("url"); string username = pros.getproperty("username"); string password = pros.getproperty("password"); string driverclass = pros.getproperty("driverclass"); // 加载驱动 class.forname(driverclass); // 获取连接 connection conn = drivermanager.getconnection(url, username, password); // 定义查询语句 string sql = "select inet_server_addr(),pg_is_in_recovery(),current_database(),current_user"; preparedstatement ps = conn.preparestatement(sql); // 执行查询并返回结果集 resultset rs = ps.executequery(); // 处理结果集 while (rs.next()) { system.out.println("inet_server_addr: " rs.getstring(1)); system.out.println("pg_is_in_recovery: " rs.getstring(2)); system.out.println("current_database: " rs.getstring(3)); system.out.println("current_user: " rs.getstring(4)); } // 关闭资源 rs.close(); ps.close(); conn.close(); } } [root@pgtest3 ~]# vi jdbc.properties url=jdbc:postgresql://192.168.58.20:5000/postgres username=postgres password=postgres driverclass=org.postgresql.driver [root@pgtest3 ~]# javac postgresqljdbc.java [root@pgtest3 ~]# java postgresqljdbc -cp /enmo/soft/postgresql-42.2.20.jar inet_server_addr: 192.168.58.10 pg_is_in_recovery: f current_database: postgres current_user: postgres

  除了标准连接参数之外,驱动程序还支持许多附加属性,这些属性可用于指定特定于 postgresql 的附加驱动程序行为。 这些属性可以在连接 url 或 drivermanager.getconnection 的附加属性对象参数中指定。
  如果在 url 和 properties 对象中都指定了同一个属性,则忽略 properties 对象中的值,本小节下方有测试案例证明此说法。
  详情参考postgresql jdbc driver 官方文档:

| property | type | default | description | | ----------------------------- | ------- | :-----: | ------------- | | user | string | null | the database user on whose behalf the connection is being made. | | password | string | null | the database user's password. | | options | string | null | specify 'options' connection initialization parameter. | | ssl | boolean | false | control use of ssl (true value causes ssl to be required) | | sslfactory | string | null | provide a sslsocketfactory class when using ssl. | | sslfactoryarg (deprecated) | string | null | argument forwarded to constructor of sslsocketfactory class. | | sslmode | string | prefer | controls the preference for opening using an ssl encrypted connection. | | sslcert | string | null | the location of the client's ssl certificate | | sslkey | string | null | the location of the client's pkcs#8 ssl key | | sslrootcert | string | null | the location of the root certificate for authenticating the server. | | sslhostnameverifier | string | null | the name of a class (for use in [class.forname(string)](https://docs.oracle.com/javase/6/docs/api/java/lang/class.html#forname(java.lang.string))) that implements javax.net.ssl.hostnameverifier and can verify the server hostname. | | sslpasswordcallback | string | null | the name of a class (for use in [class.forname(string)](https://docs.oracle.com/javase/6/docs/api/java/lang/class.html#forname(java.lang.string))) that implements javax.security.auth.callback.callbackhandler and can handle passwordcallback for the ssl password. | | sslpassword | string | null | the password for the client's ssl key (ignored if sslpasswordcallback is set) | | sendbuffersize | integer | -1 | socket write buffer size | | receivebuffersize | integer | -1 | socket read buffer size | | loggerlevel | string | null | logger level of the driver using java.util.logging. allowed values: off, debug or trace. | | loggerfile | string | null | file name output of the logger, if set, the logger will use a filehandler to write to a specified file. if the parameter is not set or the file can't be created the consolehandler will be used instead. | | allowencodingchanges | boolean | false | allow for changes in client_encoding | | logunclosedconnections | boolean | false | when connections that are not explicitly closed are garbage collected, log the stacktrace from the opening of the connection to trace the leak source | | binarytransferenable | string | "" | comma separated list of types to enable binary transfer. either oid numbers or names | | binarytransferdisable | string | "" | comma separated list of types to disable binary transfer. either oid numbers or names. overrides values in the driver default set and values set with binarytransferenable. | | preparethreshold | integer | 5 | statement prepare threshold. a value of -1 stands for forcebinary | | preparedstatementcachequeries | integer | 256 | specifies the maximum number of entries in per-connection cache of prepared statements. a value of 0 disables the cache. | | preparedstatementcachesizemib | integer | 5 | specifies the maximum size (in megabytes) of a per-connection prepared statement cache. a value of 0 disables the cache. | | defaultrowfetchsize | integer | 0 | positive number of rows that should be fetched from the database when more rows are needed for resultset by each fetch iteration | | logintimeout | integer | 0 | specify how long to wait for establishment of a database connection.| | connecttimeout | integer | 10 | the timeout value used for socket connect operations. | | sockettimeout | integer | 0 | the timeout value used for socket read operations. | | tcpkeepalive | boolean | false | enable or disable tcp keep-alive. | | applicationname | string | null | the application name (require server version >= 9.0) | | readonly | boolean | true | puts this connection in read-only mode | | disablecolumnsanitiser | boolean | false | enable optimization that disables column name sanitiser | | assumeminserverversion | string | null | assume the server is at least that version | | currentschema | string | null | specify the schema (or several schema separated by commas) to be set in the search-path | | targetservertype | string | any | specifies what kind of server to connect, possible values: any, master, slave (deprecated), secondary, preferslave (deprecated), prefersecondary | | hostrecheckseconds | integer | 10 | specifies period (seconds) after which the host status is checked again in case it has changed | | loadbalancehosts | boolean | false | if disabled hosts are connected in the given order. if enabled hosts are chosen randomly from the set of suitable candidates | | socketfactory | string | null | specify a socket factory for socket creation | | socketfactoryarg (deprecated) | string | null | argument forwarded to constructor of socketfactory class. | | autosave | string | never | specifies what the driver should do if a query fails, possible values: always, never, conservative | | cleanupsavepoints | boolean | false | in autosave mode the driver sets a savepoint for every query. it is possible to exhaust the server shared buffers. setting this to true will release each savepoint at the cost of an additional round trip. | | preferquerymode | string | extended | specifies which mode is used to execute queries to database, possible values: extended, extendedforprepared, extendedcacheeverything, simple | | rewritebatchedinserts | boolean | false | enable optimization to rewrite and collapse compatible insert statements that are batched. | | escapesyntaxcallmode | string | select | specifies how jdbc escape call syntax is transformed into underlying sql (call/select), for invoking procedures or functions (requires server version >= 11), possible values: select, callifnoreturn, call | | maxresultbuffer | string | null | specifies size of result buffer in bytes, which can't be exceeded during reading result set. can be specified as particular size (i.e. "100", "200m" "2g") or as percent of max heap memory (i.e. "10p", "20pct", "50percent") | | gssencmode | string | allow | controls the preference for using gssapi encryption for the connection, values are disable, allow, prefer, and require |

  简单测试,properties对象中定义的username=benchmarksql,password=changeme,url中定义了user=postgres&password=postgres,与数据库建立连接时使用的是url中的用户名和密码。

[[email protected] ~]# vi jdbc.properties url=jdbc:postgresql://192.168.58.20:5000/benchmarksql?user=postgres&password=postgres username=benchmarksql password=changeme driverclass=org.postgresql.driver [[email protected] ~]# java postgresqljdbc -cp /enmo/soft/postgresql-42.2.20.jar inet_server_addr: 192.168.58.10 pg_is_in_recovery: f current_database: benchmarksql current_user: postgres # 使用url中的用户建立连接
  • 支持连接的故障转移,连接串配置如下,驱动程序将依次尝试连接到它们中的每一个,直到连接成功。 如果没有成功,则抛出连接异常。
    jdbc:postgresql://host1:port1,host2:port2/database
# 192.168.58.10是主节点,192.168.58.11/12是只读从节点 [[email protected] ~]# vi jdbc.properties url=jdbc:postgresql://192.168.58.10:5432,192.168.58.11:5432,192.168.58.12:5432/benchmarksql username=postgres password=postgres driverclass=org.postgresql.driver [[email protected] ~]# java postgresqljdbc -cp /enmo/soft/postgresql-42.2.20.jar inet_server_addr: 192.168.58.10 pg_is_in_recovery: f current_database: benchmarksql current_user: postgres # 关闭主库 [[email protected] ~]# patronictl pause success: cluster management is paused [[email protected] ~]# su - postgres [[email protected] ~]$ pg_ctl stop waiting for server to shut down....... done server stopped # 连接故障转移到其他节点 [[email protected] ~]# java postgresqljdbc -cp /enmo/soft/postgresql-42.2.20.jar inet_server_addr: 192.168.58.11 pg_is_in_recovery: t current_database: benchmarksql current_user: postgres

  在针对每个节点上具有相同数据的 postgresql 高可用性时,故障转移非常有用。 例如 replication postgres 或 postgres-xc 集群。

  • 一个应用程序可以创建两个连接池。 一个连接池用于写入,另一个用于读取。 写入的连接池限制仅连接到一个主节点:
    jdbc:postgresql://node1,node2,node3/accounting?targetservertype=primary
# 192.168.58.10是主节点,192.168.58.11/12是只读从节点 [[email protected] ~]# vi jdbc.properties url=jdbc:postgresql://192.168.58.10:5432,192.168.58.11:5432,192.168.58.12:5432/benchmarksql?targetservertype=primary username=postgres password=postgres driverclass=org.postgresql.driver [[email protected] ~]# java postgresqljdbc -cp /enmo/soft/postgresql-42.2.20.jar inet_server_addr: 192.168.58.10 # 连接主库 pg_is_in_recovery: f current_database: benchmarksql current_user: postgres # 将 192.168.58.11:5432 放到第一位 [[email protected] ~]# vi jdbc.properties url=jdbc:postgresql://192.168.58.11:5432,192.168.58.10:5432,192.168.58.12:5432/benchmarksql?targetservertype=primary username=postgres password=postgres driverclass=org.postgresql.driver [[email protected] ~]# java postgresqljdbc -cp /enmo/soft/postgresql-42.2.20.jar inet_server_addr: 192.168.58.10 # 连接还是主库,说明targetservertype可以判断数据库是主还是从 pg_is_in_recovery: f current_database: benchmarksql current_user: postgres

用于读取的连接池负载均衡节点之间的连接,但如果没有只读从节点可用,也允许连接到主节点:
jdbc:postgresql://node1,node2,node3/accounting?targetservertype=prefersecondary&loadbalancehosts=true

# 192.168.58.10是主节点,192.168.58.11/12是只读从节点 [[email protected] ~]# vi jdbc.properties url=jdbc:postgresql://192.168.58.10:5432,192.168.58.11:5432,192.168.58.12:5432/benchmarksql?targetservertype=prefersecondary&loadbalancehosts=true username=postgres password=postgres driverclass=org.postgresql.driver [[email protected] ~]# java postgresqljdbc -cp /enmo/soft/postgresql-42.2.20.jar inet_server_addr: 192.168.58.11 # 连接只读从节点 pg_is_in_recovery: t current_database: benchmarksql current_user: postgres [[email protected] ~]# java postgresqljdbc -cp /enmo/soft/postgresql-42.2.20.jar inet_server_addr: 192.168.58.12 # 负载均衡连到另一个从节点 pg_is_in_recovery: t current_database: benchmarksql current_user: postgres # 关闭一个从节点 [[email protected] ~]# systemctl stop patroni.service [[email protected] ~]# java postgresqljdbc -cp /enmo/soft/postgresql-42.2.20.jar inet_server_addr: 192.168.58.12 # 多次执行,均只连另一个从库 pg_is_in_recovery: t current_database: benchmarksql current_user: postgres # 关闭所有从节点,只保留主节点 [[email protected] ~]# systemctl stop patroni.service [[email protected] ~]# java postgresqljdbc -cp /enmo/soft/postgresql-42.2.20.jar inet_server_addr: 192.168.58.10 # 连接主库 pg_is_in_recovery: f current_database: benchmarksql current_user: postgres
最后修改时间:2021-11-06 16:42:07
「喜欢文章,快来给作者赞赏墨值吧」
1人已赞赏
【利来手机国际的版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:[email protected]进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论