我创建了一个正在运行的Cloud Sql实例。我一直在尝试通过Android Studio和Eclipse连接到它,但在这两个地方都失败了。
package com.example.testapplication3;
import java.sql.*;
public class ConnectToSql {
public String run()
{
try {
Class.forName("com.mysql.cj.jdbc.Driver");
String instanceConnectionName = "TheActualInstanceName";
String databaseName = "BudgetApp";
String IP_of_instance = "35.******";
String username = "root";
String password = "********";
String jdbcUrl = String.format("jdbc:mysql://%s/%s?cloudSqlInstance=%s" +
"&socketFactory=com.google.cloud.sql.mysql.SocketFactory&useSSL=false",
IP_of_instance, databaseName, instanceConnectionName);
Connection connection = DriverManager.getConnection(jdbcUrl, username, password);
Statement stat = connection.createStatement();
ResultSet res = stat.executeQuery("Select * from users;");
String result = "";
while (res.next())
{
result += (res.getString(1) + " " + res.getString(2) + " " + res.getString(3));
}
connection.close();
return result;
}
catch(Exception e)
{
System.out.println(e);
return null;
}
}
}
我不断从中收到此错误:
java.sql.SQLNonTransientConnectionException: Cannot connect to MySQL server on 35.*******:3,306.
Make sure that there is a MySQL server running on the machine/port you are trying to connect to and that the machine this software is running on is able to connect to this host/port (i.e. not firewalled). Also make sure that the server has not been started with the --skip-networking flag.
我做了什么:
- 确保我的 IP 在"实例连接"选项卡下已列入白名单
- 网址连接的不同格式
- 已通过 ping 确保服务器已启动
- 仅通过云外壳连接
- 已确认端口在云端打开
您应该遵循从外部应用程序连接到 Cloud SQL 的指南。你应该使用Cloud SQL jdbc套接字工厂,因为我猜你已经在使用。
从您的代码中,我可以看到jdbc url看起来有点奇怪。请尝试将其更改为此确切格式,请:
jdbc:mysql://google/<DATABASE_NAME>?cloudSqlInstance=<INSTANCE_CONNECTION_NAME>&socketFactory=com.google.cloud.sql.mysql.SocketFactory&useSSL=false&user=<MYSQL_USER_NAME>&password=<MYSQL_USER_PASSWORD>
您缺少"谷歌"部分。 希望这会有所帮助!如果这不起作用,则可能值得尝试通过Cloud SQL代理进行连接,如我在此处附加的第一个链接所示。