Connecting to the Database
After a database connection is created, you can use it to execute SQL statements.
Function Prototypes
JDBC provides three methods for creating a database connection.
DriverManager.getConnection(String url);
DriverManager.getConnection(String url, Properties info);
DriverManager.getConnection(String url, String user, String password);
Example
java
// The following code encapsulates the database connection operation as an interface, allowing connection to the database via the user name and password.
public static Connection getConnect(String username, String passwd) {
// Driver class.
String driver = "org.opengauss.Driver";
// Database connection descriptor.
String sourceURL = "jdbc:oGRAC://127.0.0.1:8000";
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 a 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:oGRAC://127.0.0.1:8000";
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;
}