我使用此代码 但是,有人可以建议我或指导我一个正确的文档,它可以给我一个如何用JDBC连接到heroku postgress数据库的例子吗?
URI dbUri = new URI(System.getenv("DATABASE_URL"));
String dbUrl = "jdbc:postgresql://" + dbUri.getHost() +
dbUri.getPath();
connectionPool = new BasicDataSource();
if (dbUri.getUserInfo() != null) {
connectionPool.setUsername(dbUri.getUserInfo().split(":")[0]);
connectionPool.setPassword(dbUri.getUserInfo().split(":")[1]);
}
connectionPool.setDriverClassName("org.postgresql.Driver");
connectionPool.setUrl(dbUrl);
connectionPool.setInitialSize(1);
Connection connection = connectionPool.getConnection();
答案 0 :(得分:0)
请参阅heroku的documentation
注意:
Heroku Postgres附加组件的DATABASE_URL
遵循以下惯例
postgres://<username>:<password>@<host>:<port>/<dbname>
然而,Postgres JDBC驱动程序使用以下约定:
jdbc:postgresql://<host>:<port>/<dbname>?user=<username>&password=<password>
将DATABASE_URL解析为Jdbc格式的示例代码:
private static Connection getConnection() throws URISyntaxException, SQLException {
URI dbUri = new URI(System.getenv("DATABASE_URL"));
String username = dbUri.getUserInfo().split(":")[0];
String password = dbUri.getUserInfo().split(":")[1];
String dbUrl = "jdbc:postgresql://" + dbUri.getHost() + ':' + dbUri.getPort() + dbUri.getPath();
return DriverManager.getConnection(dbUrl, username, password);
}