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.
To connect to a database in UDS mode, perform the following steps:
- 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 API Reference.
import java.sql.Connection; import java.sql.DriverManager; import java.util.Properties;
- 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);
- Load the driver.
- Add the opengaussjdbc.jar package to the code running tool (such as IDE).
- Load the database driver com.huawei.opengauss.jdbc.Driver as follows:
String driver = "com.huawei.opengauss.jdbc.Driver"; Class.forName(driver);
- Specify the database $ip, $port, database, socketFactory, and socketFactoryArg.
Change $ip, $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.
Set the socketFactoryArg parameter based on the actual path. The value must be the same as that of the GUC parameter unix_socket_directory.
Connection conn = DriverManager.getConnection("jdbc:opengauss://$ip:$port/database?socketFactory=org.newsclub.net.unix" + ".AFUNIXSocketFactory$FactoryArg&socketFactoryArg=[path-to-the-unix-socket]",properties); System.out.println("Connection Successful!");
Feedback
Was this page helpful?
Provide feedbackThank you very much for your feedback. We will continue working to improve the documentation.See the reply and handling status in My Cloud VOC.
For any further questions, feel free to contact us through the chatbot.
Chatbot