Connecting to Google cloud sql from Java stand alone application

后端 未结 2 834
醉话见心
醉话见心 2020-12-22 05:59

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 a s

相关标签:
2条回答
  • 2020-12-22 06:50

    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();
    }
    }
    }
    
    0 讨论(0)
  • 2020-12-22 06:51

    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 this link https://cloud.google.com/sql/docs/external for more information.

    0 讨论(0)
提交回复
热议问题