Updated on 2025-03-13 GMT+08:00

Connecting to a Database in UDS Mode

The UDS is used for data exchange between different processes on the same host. You can add junixsocket to obtain the socket factory.

Prerequisites: You have referenced junixsocket-core-XXX.jar, junixsocket-common-XXX.jar, and junixsocket-native-common-XXX.jar. XXX indicates the version number. The version numbers of the referenced JAR packages must be consistent.

The following uses opengaussjdbc.jar as an example to describe how to connect to a database through a UDS as follows:

  1. Import java.sql.Connection, java.sql.DriverManager, and java.util.Properties.

    In addition, you need to import other APIs and classes based on the actual application scenario. For details, see JDBC Interface Reference.
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.util.Properties;

  2. Specify the username and password of the database.

    Writing the username and password to code has great security risks. You are advised to store the username and password in environment variables. Set the username and password to the property values of the Properties object.
    String userName = System.getenv("EXAMPLE_USERNAME_ENV");
    String password = System.getenv("EXAMPLE_PASSWORD_ENV");
    Properties properties = new Properties();
    properties.setProperty("user", userName);
    properties.setProperty("password", password);

  3. Load the driver.

    1. Add the opengaussjdbc.jar package to the code running tool (such as IDE).
    2. Load the database driver com.huawei.opengauss.jdbc.Driver as follows:
    String driver = "com.huawei.opengauss.jdbc.Driver";
    Class.forName(driver);

  4. Specify the database $ip, $port, database, socketFactory, and socketFactoryArg.

    Change $ip and $port as required. Set database to localhost, socketFactory to org.newsclub.net.unix.AFUNIXSocketFactory$FactoryArg, and socketFactoryArg to [path-to-the-unix-socket] to connect to the database in UDS mode. For details about the socketFactory and socketFactoryArg parameters, see socketFactory and socketFactoryArg.

    Connection conn = DriverManager.getConnection("jdbc:opengauss://$ip:$port/localhost?socketFactory=org.newsclub.net.unix" +
            ".AFUNIXSocketFactory$FactoryArg&socketFactoryArg=[path-to-the-unix-socket]",properties);
    System.out.println("Connection Successful!");

    Set the socketFactoryArg parameter based on the actual path. The value must be the same as that of the GUC parameter unix_socket_directory.