I want to connect to cloud sql postgres db from java program running in Kubernetes pod. i read on internet there are several ways like using google cloud sql auth proxy etc but i wanted to if its possible to just connect via plain jdbc method using service account or WIF.
currently i am running below program on my local and i am able to connect using it because my user have Cloud SQL Instance User role. But wanted to check how it works when i run in pod.
String jdbcUrl = “jdbc:postgresql://10.18.240.3:5432/”+databaseName;
// Properties for connection
Properties properties = new Properties();
properties.setProperty("user", username);
properties.setProperty("password", password);
// Enable SSL and configure certificate files
properties.setProperty("ssl", "true");
properties.setProperty("sslmode", "verify-ca"); // Use 'verify-full' or 'require'
properties.setProperty("sslrootcert", sslCaCertPath);
properties.setProperty("sslcert", sslCertPath);
properties.setProperty("sslkey", sslKeyPath);
try {
// Load PostgreSQL JDBC driver
Class.forName("org.postgresql.Driver");
// Establish connection
String query = "SELECT NOW()";
try (Connection connection = DriverManager.getConnection(jdbcUrl, properties);
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(query)) {
if (resultSet.next()) {
System.out.println("Current time from database: " + resultSet.getString(1));
}
} catch (Exception e) {
e.printStackTrace();
}
// Connection successful
System.out.println("Connected to the PostgreSQL server successfully.");
Varun Agrawal is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.