我使用 App Engine 创建了一个 java web servlet,该 servlet 向数据库发出请求。我已经使用本地数据库在本地测试了 servlet,它运行良好,然后我继续在本地测试 servlet,但访问了 Cloud SQL 数据库,这也运行良好。
我的问题出现在我部署 servlet 之后。部署后,所有数据库请求都会返回以下内容:
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.
我在云控制台中进行了检查,我的应用程序已正确添加到“访问控制”选项卡下的云 SQL 授权 App 引擎应用程序中。
有没有人遇到过部署的应用程序引擎 servlet 的类似问题?有什么解决方案或建议吗?我将不胜感激任何帮助!!!
更新:
上面的错误是使用下面的代码访问数据库产生的
Class.forName("com.mysql.jdbc.Driver");
Url = "jdbc:mysql://<ip-address-cloudsql>:3306/<dbname>";
Connection con = DriverManager.getConnection (Url,"root",<password>);
使用此代码也出现了同样的错误,请注意,它与此处示例中显示的代码非常相似 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);
在使用 appid 和实例 id 设置 url 时,我遵循了这篇 stackoverflow 帖子中显示的格式提示: com.mysql.jdbc.exceptions.jdbc4.CommunicationsException:
使用此代码会导致以下不同的错误:
java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)
我假设它说的是 localhost,因为我的 cloudsql 数据库设置为遵循 App Engine servlet。另外,要知道在本地运行 servlet 和访问云 sql 数据库时,这两种方法都可以正常工作。
有什么想法吗?我不知道还能尝试什么:[
最佳答案
从授权的 App Engine 应用程序连接到 Cloud SQL 时,不需要密码(实际上,如果您尝试使用密码连接会失败)。
将连接字符串更改为 jdbc:google:mysql://<appID:instanceID>/<dbname>?
user=root
省略 &password=<password>
部分
关于java - App Engine Java Servlet 不连接到 Cloud SQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20896237/