PostgreSQL JDBC 连接参数设置
在标准的连接参数之外,JDBC 驱动还支持很多额外的参数设置,这些参数有些与 PostgreSQL 数据库的具体功能相关。连接参数可以在连接地址的 url 中设置,也可以通过 Properties 对象进行设置。如果 url 和 Properties 对象都设置了同一个参数,那么 url 的优先级更高,Properties 设置的参数将被忽略。
下面通过示例介绍 jdbc 连接参数的设置。
1. 连接字符串 url 中设置连接参数
可以将额外的连接参数放在 url 连接字符串中设置,比如将连接数据库的用户 user 和密码 password 放到 url 中,多个参数使用 & 进行连接,那么在 DriverManager.getConnection() 调用中只需要传入 url 即可,不需要再传入用户和密码参数,如下:
String url = "jdbc:postgresql://127.0.0.1:36099/postgres?user=admin&password=123456"; Connection connection = DriverManager.getConnection(url);
完整示例代码如下:
import java.sql.*;
public class Main{
public static void main(String[] args)
{
String url = "jdbc:postgresql://127.0.0.1:36099/postgres?user=admin&password=123456";
Connection connection = null;
PreparedStatement pStatement = null;
ResultSet rs = null;
try {
connection = DriverManager.getConnection(url);
pStatement = connection.prepareStatement("select version()");
rs = pStatement.executeQuery();
while(rs.next()){
String version = rs.getString("version");
System.out.println("version:" + version);
}
connection.close();
}catch (SQLException e) {
e.printStackTrace();
}
}
}
2. 通过 Properties 设置连接参数
创建 Properties 对象,调用 setProperty() 方法设置连接参数。在调用 DriverManager.getConnection() 创建连接时需要传入 url 和 Properties 对象,如下所示:
Properties props = new Properties();
props.setProperty("user", "admin");
props.setProperty("password", "123456");
Connection connection = DriverManager.getConnection(url, props);
完整示例代码:
import java.sql.*;
import java.util.Properties;
public class Main{
public static void main(String[] args)
{
String url = "jdbc:postgresql://127.0.0.1:36099/postgres";
Properties props = new Properties();
props.setProperty("user", "admin");
props.setProperty("password", "123456");
Connection connection = null;
PreparedStatement pStatement = null;
ResultSet rs = null;
try {
connection = DriverManager.getConnection(url, props);
pStatement = connection.prepareStatement("select version()");
rs = pStatement.executeQuery();
while(rs.next()){
String version = rs.getString("version");
System.out.println("version:" + version);
}
connection.close();
}catch (SQLException e) {
e.printStackTrace();
}
}
}
3. 包含特殊字符的连接参数值
如果在 url 中设置连接参数,参数的值包含空格或其他特殊字符时则需要进行转码。空格被视为分隔命令行参数,需要对其进行转码,将空格转成 %20,如下:
roperties props = new Properties();
props.setProperty("options", "-c search_path=test,public,pg_catalog -c statement_timeout=90000");
Connection conn = DriverManager.getConnection(url, props);
String url = "jdbc:postgresql://localhost:5432/postgres?options=-c%20search_path=test,public,pg_catalog%20-c%20statement_timeout=90000";
Connection conn = DriverManager.getConnection(url); 文章评论
共0条评论