openGauss Connecting to a Database
After a database is connected, you can use JDBC to run SQL statements to operate data.
Function Prototype
JDBC provides the following three database connection methods:
DriverManager.getConnection(String url);
DriverManager.getConnection(String url, Properties info);
DriverManager.getConnection(String url, String user, String password);
Parameters
Table 1 Database connection parameters
Parameter | Description |
url | postgresql.jar database connection descriptor. The format is as follows: |
info | Database connection attributes (all attributes are case sensitive). Common attributes are described as follows: |
user | Database user. |
password | Password of the database user. |
NOTE: After the uppercaseAttributeName parameter is enabled, if the database contains metadata with a mixture of uppercase and lowercase letters, only the metadata in lowercase letters can be queried and output in uppercase letters. Before using the metadata, ensure that the metadata is stored in lowercase letters to prevent data errors.
Examples
// The following code encapsulates database connection operations into an API. The database can then be connected using an authorized username and a password.
public static Connection getConnect(String username, String passwd)
{
// Driver class.
String driver = "org.opengauss.Driver";
// Database connection descriptor.
String sourceURL = "jdbc:opengauss://10.10.0.13:8000/postgres";
Connection conn = null;
try
{
// Load the driver.
Class.forName(driver);
}
catch( Exception e )
{
e.printStackTrace();
return null;
}
try
{
// Create a connection.
conn = DriverManager.getConnection(sourceURL, username, passwd);
System.out.println("Connection succeed!");
}
catch(Exception e)
{
e.printStackTrace();
return null;
}
return conn;
};
// The following code uses the Properties object as a parameter to establish a connection.
public static Connection getConnectUseProp(String username, String passwd)
{
// Driver class.
String driver = "org.opengauss.Driver";
// Database connection descriptor.
String sourceURL = "jdbc:opengauss://10.10.0.13:8000/postgres?";
Connection conn = null;
Properties info = new Properties();
try
{
// Load the driver.
Class.forName(driver);
}
catch( Exception e )
{
e.printStackTrace();
return null;
}
try
{
info.setProperty("user", username);
info.setProperty("password", passwd);
// Create a connection.
conn = DriverManager.getConnection(sourceURL, info);
System.out.println("Connection succeed!");
}
catch(Exception e)
{
e.printStackTrace();
return null;
}
return conn;
};