URL用于标识数据库的位置,通过URL地址告诉JDBC程序连接哪个数据库,postgre jdbc支持的URL的写法为:
- jdbc:postgresql:database
- jdbc:postgresql:/
- jdbc:postgresql://host/database
- jdbc:postgresql://host/
- jdbc:postgresql://host:port/database
- jdbc:postgresql://host:port/
- jdbc:postgresql://host1:port1,host2:port2/database
- ipv6地址:jdbc:postgresql://[::1]:5740/accounting
也可以在url中加入其他参数如:?uer=root&password=root&useUnicode=true&characterEncoding=utf8
1、 接受url、与一个持久化属性集对象,相应参入可放入properties中
String url="jdbc:postgresql://localhost:5432/test"
Properties info = new Properties(); //定义Properties对象
info.setProperty("user","root"); //设置Properties对象属性
info.setProperty("password","root");
Connection con = DriverManager.getConnection(url,info);
源码如下:
@CallerSensitive
public static Connection getConnection(String url,
java.util.Properties info) throws SQLExce
ption {
return (getConnection(url, info, Reflection.getCallerClass()));
}
2、只接受一个url,用户名密码及其他相关设置都以url参数的形式放入
String url = "
jdbc:postgresql
://localhost:5432/test?user=root&password=root
";
Connection con = DriverManager.getConnection(url);
源码如下:
@CallerSensitive
public static Connection getConnection(String url)
throws SQLException {
java.util.Properties info = new java.util.Properties();
return (getConnection(url, info, Reflection.getCallerClass()));
}
3、接受一个url和String类型的user与password,其他参数以url参数形式放入
String url = "jdbc:postgresql://localhost:5432/test";
Connection con = DriverManager.getConnection(url,"root","root");
源码如下:
@CallerSensitive
public static Connection getConnection(String url,
String user, String password) throws SQLException {
java.util.Properties info = new java.util.Properties();
if (user != null) {
info.put("user", user);
}
if (password != null) {
info.put("password", password);
}
return (getConnection(url, info, Reflection.getCallerClass()));
}