Gabriel Khaselev Gabriel Khaselev - 7 months ago 19
Java Question

App Engine Java Servlet does not connect to Cloud SQL

I have created a java web servlet using app engine, the servlet makes requests to a database. I have tested the servlet locally using a local database and it worked perfectly, i then proceeded to test the servlet locally but istead accessed the Cloud SQL database, this also worked perfectly.

My problem arises after i deploy the servlet. Once deployed all database requests return the following:

com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure

The last packet sent successfully to the server was 0 milliseconds ago. The driver has not
received any packets from the server.


I checked within the cloud console, and my app was properly added to the cloud SQL Authorized App Engine Applications under the Access Control tab.

Has anyone had similar problems with deployed app engine servlets? Any solutions or advice out there? I would appreciate any and all help!!!

UPDATE:

The above error was generated using the following code to access the db

Class.forName("com.mysql.jdbc.Driver");
Url = "jdbc:mysql://<ip-address-cloudsql>:3306/<dbname>";
Connection con = DriverManager.getConnection (Url,"root",<password>);


the same error was acheived using this code, note that it is very similar to the code shown in the example here https://developers.google.com/appengine/docs/java/cloud-sql/

Class.forName("com.mysql.jdbc.GoogleDriver");
Url = "jdbc:google:mysql://<appID:instanceID>/<dbname>?
user=root&password=<password>";
Connection con = DriverManager.getConnection (Url);


I followed the formatting tips show in this stackoverflow post when it came to setting the url using appid and instance id:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:

Using this code resulted in the following different error:

java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)


I'm assuming it says localhost because my cloudsql database is set to follow the app engine servlet. Also, know that both of these methods worked fine when running the servlet locally and accessing the cloud sql database.

any thoughts? i don't know what else to try:[

Answer

When connecting to Cloud SQL from an authorized App Engine application, the password is not required (actually it will fail if you try to connect with password).

Change your connection string to jdbc:google:mysql://<appID:instanceID>/<dbname>? user=root omitting the &password=<password> part