Tianbo
Tianbo

Reputation: 77

No suitable driver found for jdbc:mysql://google/mysql?cloudSqlInstance

I know it is a common question, and I did search a lot in StackOverflow, most of the advice is to read connect to google cloud via jdbc. I followed the sample code, and I still get no suitable driver found for 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 is the only class in the project, and I did not use any external library except Java 1.8.

I can use MySQL Workbench connect to Google Cloud MySQL instance, so I think it is not the authentication problem.

Which step is wrong? Any suggestion will be helpful, thank you in advance!

Upvotes: 1

Views: 1005

Answers (2)

aaronvargas
aaronvargas

Reputation: 14152

add this before you call DriverManager.getConnection() otherwise it won't be a 'registered driver'

Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
// for older 5.x mysql-connector  Class.forName("com.mysql.jdbc.Driver").newInstance();

See https://dev.mysql.com/doc/connector-j/8.0/en/connector-j-usagenotes-connect-drivermanager.html

Upvotes: 0

Alan Blyth
Alan Blyth

Reputation: 195

Add this library manually or to your POM:

<dependency>
        <groupId>com.google.cloud.sql</groupId>
        <artifactId>mysql-socket-factory</artifactId>
        <version>1.0.5</version>
</dependency>

For me this resolved the issue where the Connection couldn't find a suitable Driver.

Upvotes: 1

Related Questions