我如何在没有应用引擎的情况下连接谷歌云实例

我正在尝试连接到谷歌云实例,但遇到了一些麻烦。我很感激帮助找到最简单的方法。


我也是使用数据库和 Java 的新手。


这是我的代码:


package com.google.cloud.sql.mysql;


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 example{

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

// TODO: fill this in

// The instance connection name can be obtained from the instance overview page in Cloud Console

// or by running "gcloud sql instances describe <instance> | grep connectionName".

String instanceConnectionName = "eco-codex-216813:asia-southeast1:instance1";


// TODO: fill this in

// The database from which to list tables.

String databaseName = "mysql";


String username = "root";


// TODO: fill this in

// This is the password that was set via the Cloud Console or empty if never set

// (not recommended).

String password = "1412";



//[START doc-example]

String jdbcUrl = String.format(

    "jdbc:mysql://google/%s?cloudSqlInstance=%s"

        + "&socketFactory=com.google.cloud.sql.mysql.SocketFactory&useSSL=false",

    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));

    }

   }

  }

}


阿晨1998
浏览 141回答 1
1回答

DIEA

欢迎使用 Stackoverflow 和 Google Cloud!我假设您的意思是带有“Google 云实例”的带有 MySQL 引擎的 Google Cloud SQL 实例。您需要打开从运行 Java 程序的机器到 Cloud SQL 实例的网络级别访问权限。在 Cloud SQL 中,默认行为是阻止外部访问。您可以在云控制台中编辑实例,并在“授权网络”部分添加您的 IP 地址或 IP 范围以允许连接。如果您的 Java 机器和 Cloud SQL 之间没有其他防火墙,您应该能够在此更改后进行连接。希望能帮助到你!您可以从此页面找到有关 Cloud SQL 连接的更多信息:https&nbsp;:&nbsp;//cloud.google.com/sql/docs/mysql/connect-external-app#appaccessIP。您还可以找到连接到数据库的其他选项,例如使用代理。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java