Search code examples
javajdbcgoogle-cloud-sql

Connecting to Google SQL with a simple Java program (JDBC)


I have a simple Java program (not a web application/Google Engine/etc.). I went over every guide in Google Cloud SQL website, and I can't figure out how to connect to the server.

Right now I have

Class.forName("com.mysql.jdbc.Driver");

and

connection = DriverManager.getConnection("jdbc:mysql://x:3306/y?user=root"); 

Where x is IP address of the instance (taken from the properties of the instance) and y is simply the instance ID.

Am I doing something wrong? I also set a password for the root as one of the tutorials suggested. Should I specify it somewhere in the code?

Thanks.

EDIT

Following mohan rathour's link, I obtained Cloud SQL MySQL Socket Factory and my code now looks like:

Class.forName("com.mysql.jdbc.Driver");

and

String jdbcUrl = String.format("jdbc:mysql://google/%s?cloudSqlInstance=%s&"+"socketFactory=com.google.cloud.sql.mysql.SocketFactory",
                    "dbname",
                    "instanceConnectionName");

connection = DriverManager.getConnection(jdbcUrl, "userName", "password");

I get the following in my console:

INFO: Connecting to Cloud SQL instance [instanceName].
com.google.cloud.sql.mysql.SslSocketFactory getInstance
INFO: First Cloud SQL connection, generating RSA key pair.

But then I get this exception:

com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: Could not create connection to database server.

SOLUTION

No need to use "Cloud SQL MySQL Socket Factory".

In the Google SQL panel, go to your instance panel -> Access Control -> Authorization, add the following network address and click save.

0.0.0.0/0

Now you can connect with this code:

Class.forName("com.mysql.jdbc.Driver");
...
String url= String.format("jdbc:mysql://x:3306/y");
connection = DriverManager.getConnection(url, z, w);

Where x is your instance IP (get it from the panel), y is the instance name, z is the database (not account) user name (usually "root") and w is the user password (you have to set it. look at Google's tutorials).


Solution

  • By default, Cloud SQL instances do not allow connections on the public IP. You must add individual subnets from which you would like to connect. You can see the full documentation here: https://cloud.google.com/sql/docs/external#appaccessIP

    An alternative that does not require whitelisting IP addresses is using the Cloud SQL Socket Library that uses an SSL session with short-lived certs: https://cloud.google.com/sql/docs/external#java

    Whitelisting 0.0.0.0/0 is not recommended as it opens the database to the entire world.