java 解析postgres URL

bqjvbblv  于 2023-04-19  发布在  Java
关注(0)|答案(3)|浏览(159)

我正在尝试解析postgres db凭据,格式如下:
postgres://usernname:password@hostaddress:port/databasename
我调用了一个方法,它以一行字符串的形式返回这些凭据,并试图找出是否有一种简单的方法来通过用户名、密码端口等来解析它们,而不是使用正则表达式。

qmelpv7a

qmelpv7a1#

正如@OneCricketeer的评论中所建议的那样-你可以使用URI解析器来做这种事情,在我看来这也是最好的解决方案。你可以这样实现它:

try {
    URI uri = new URI("postgres://username:password@host.com:123/databasename");
    String[] userAndPassword = uri.getUserInfo().split(":");
    String user = userAndPassword[0];
    String password = userAndPassword[1];
    String host = uri.getHost();
    int port = uri.getPort();
    String database = uri.getPath().substring(1);
} catch (URISyntaxException e) {
    e.printStackTrace(); // handle invalid JDBC URL syntax
}

还可以考虑JDBC URL -也许你可以在配置中单独保留这些参数,并将JDBC URL创建为这些参数的连接?这会使事情变得更容易-这样你就不需要从URL中提取任何参数。
下面是我以前的答案(这比使用URI解析器更糟糕,但我留下它只是为了与上面的解决方案进行比较):
我会选择正则表达式,在这种情况下它并不难,然后很容易提取你需要的部分数据。
但是,你也可以使用String的split方法来获取你需要的String的一部分,比如:

String url = "postgres://username:password@hostaddress:port/databasename";
String[] urlSplitByColon = url.split(":");
String[] passwordAndHost = urlSplitByColon[2].split("@");
String[] portAndDatabaseName = urlSplitByColon[3].split("/");

String username = urlSplitByColon[1].substring(2); // substring to cut out double slash at the beginning of username
String password = passwordAndHost[0];
String host = passwordAndHost[1];
String port = portAndDatabaseName[0];
String databaseName = portAndDatabaseName[1];

但我真的建议使用regexp。

qzlgjiam

qzlgjiam2#

在Node JS中,下面的代码可以让我连接到Heroku Postgres:

// Using URL to parse database URL parameters
  const { URL } = require('url');
  const myURL =
  new URL(process.env.DATABASE_URL);
 
  // establishing a database connection
  var { Client } = require('pg');
  var client = new Client({
    user: myURL.username, //local: postgres
    host: myURL.hostname, //local: localhost
    database: myURL.pathname.substring(1), //local: postgres
    password: myURL.password, // local: admin
    port: myURL.port,
    connectionString: process.env.DATABASE_URL,
    ssl: {
      rejectUnauthorized: false
    }
  });

为了提取数据库字符串,必须使用“substring”从路径名中删除“/”。
运行节点v16.14.2

brgchamk

brgchamk3#

import java.sql.*;
import org.postgresql.Driver;
import org.postgresql.util.PGProperty;

public class ParsePostgreConnectionString {
   public static void main(String[] args) throws SQLException {

      // Sample PostgreSQL connection string
      String connectionString = "jdbc:postgresql://localhost:5432/mydb?user=myusername&password=mypassword";

      // Register the PostgreSQL JDBC driver
      DriverManager.registerDriver(new Driver());

      // Create a Properties object and set the connection properties
      Properties props = new Properties();
      PGProperty.parseConnectionString(connectionString, props);

      // Get the individual connection properties
      String host = props.getProperty("host");
      String port = props.getProperty("port");
      String databaseName = props.getProperty("databaseName");
      String user = props.getProperty("user");
      String password = props.getProperty("password");

      // Print out the parsed connection properties
      System.out.println("Host: " + host);
      System.out.println("Port: " + port);
      System.out.println("Database name: " + databaseName);
      System.out.println("User: " + user);
      System.out.println("Password: " + password);

      // Establish a connection to the database using the parsed connection properties
      Connection conn = DriverManager.getConnection(connectionString, props);

      // Use the connection to interact with the database as needed
      // ...

      // Close the connection when finished
      conn.close();
   }
}

相关问题