The procedure for the title did not go well and it took a long time to resolve it, so I will write it as a memorandum. Basically https://cloud.google.com/sql/docs/postgres/connect-external-app?hl=ja#java If you do as follows, it will work.
The environment I went to this time Windows Subsystem for Linux Java8 sbt is. Don't worry why you're using sbt but Java. Scala is studying.
First of all, you need to install and authenticate the Cloud SDK, but I will omit it here. Next, write the required libraries in build.sbt. Please use the latest version at that time as appropriate. The following is the latest version as of December 26, 2017.
libraryDependencies ++= Seq(
"org.postgresql" % "postgresql" % "42.1.4",
"com.google.cloud.sql" % "postgres-socket-factory" % "1.0.4"
)
Then you can write a Java file like the one below and do `` `sbt run``` to connect to PostgreSQL in Cloud SQL.
import java.sql.*;
public class App {
public static void main(String[] args) throws Exception {
Connection connection = null;
String jdbcUrl = String.format(
"jdbc:postgresql://google/%s?socketFactory=com.google.cloud.sql.postgres.SocketFactory&socketFactoryArg=%s",
dbName,
instanceConnectionName);
try {
connection = DriverManager.getConnection(jdbcUrl,
userName,
password);
} finally {
if (connection != null) {
connection.close();
}
}
}
}
Here, instanceConnectionName
is the instance connection name of Cloud SQL, and it is listed on the Cloud SQL instance list screen.
Recommended Posts