Connecting to Google cloud sql from Java stand alo

2019-01-29 12:30发布

问题:

I want to write a java stand alone application to connect to Google cloud sql - Mysql database. I could find samples for app client but not for stand alone java application.

When I tried to do this, I get the following error.

Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection("jdbc:google:mysql://IP:Instance_name?user=user_name"); Statement st = con.createStatement(); ResultSet rs = con.createStatement().executeQuery("SELECT 1 + 1");

It fails with error :

No suitable driver found for jdbc:google:mysql:..

I see some answers where they have asked to enabled mysql connector. But it is the case with app engine project. How do I do it with stand alone application?

回答1:

You can just use the standard mysql connector to connect to cloud sql instance: e.g:

DriverManager.getConnection("jdbc:mysql://IP:Instance_name?user=user_name");

You can check https://cloud.google.com/sql/docs/external for more information



回答2:

Edit inside <> before running your code

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLNonTransientConnectionException;
import java.sql.Statement;

/**
* A sample app that connects to a Cloud SQL instance and lists all available tables 
in a database.
*/

public class Cloud_sql {
public static void main(String[] args) throws SQLNonTransientConnectionException 
,IOException, SQLException {

String instanceConnectionName = <Your instanceConnectionName>;
String databaseName = <Database name from which u want to list tables>;


String IP_of_instance = <IP address of the instance>;
String username = <mysql username>;
String password = <mysql 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);

try (Statement statement = connection.createStatement()) {
  ResultSet resultSet = statement.executeQuery("SHOW TABLES");
  while (resultSet.next()) {
    System.out.println(resultSet.getString(1));
  }
}catch(Exception e){
  e.printStackTrace();
}
}
}