我知道这是一个常见的问题,我在StackOverflow中搜索了很多,大部分建议是阅读connect to google cloud via jdbc。我按照示例代码,仍然没有找到适合jdbc的驱动程序。
package CSCI585HW2;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* A sample app that connects to a Cloud SQL instance and lists all available tables in a database.
*/
public class ConnectGoogleCloud {
public static void main(String[] args) throws IOException, SQLException {
String instanceConnectionName = "csci585hw2-195403:us-central1:sql-db-1";
// The database from which to list tables.
String databaseName = "test";
String username = "zongtb";
// TODO: fill this in
// This is the password that was set via the Cloud Console or empty if never set
// (not recommended).
String password = "123ewq";
//[START doc-example]
String jdbcUrl = String.format(
"jdbc:mysql://google/%s?cloudSqlInstance=%s&"
+ "socketFactory=com.google.cloud.sql.mysql.SocketFactory",
databaseName,
instanceConnectionName);
Connection connection = DriverManager.getConnection(jdbcUrl, username, password);
//[END doc-example]
try (Statement statement = connection.createStatement()) {
ResultSet resultSet = statement.executeQuery("SHOW TABLES");
while (resultSet.next()) {
System.out.println(resultSet.getString(1));
}
}
}
}
ConnectGoogleCould是项目中唯一的类,我没有使用除Java 1.8之外的任何外部库。
我可以使用MySQL Workbench连接到Google Cloud MySQL实例,所以我认为这不是身份验证问题。
哪一步错了?任何建议都会有所帮助,提前谢谢!
答案 0 :(得分:1)
手动添加此库或添加到您的POM:
<dependency>
<groupId>com.google.cloud.sql</groupId>
<artifactId>mysql-socket-factory</artifactId>
<version>1.0.5</version>
</dependency>
对我来说,这解决了Connection无法找到合适的驱动程序的问题。
答案 1 :(得分:0)
在调用DriverManager.getConnection()之前添加此代码,否则它将不是“已注册的驱动程序”
Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
// for older 5.x mysql-connector Class.forName("com.mysql.jdbc.Driver").newInstance();
请参见https://dev.mysql.com/doc/connector-j/8.0/en/connector-j-usagenotes-connect-drivermanager.html