一尘不染

从App Engine(第二代CloudSQL)GO连接到CloudSQL

go

爱堆栈,我的第一个帖子完全出于挫败感。感谢您的评论!

  • 创建了App Engine项目
  • 在我的App Engine项目中创建了第二代MySQL实例
  • 在MySQL实例中创建的数据库
  • 在App Engine中,我激活-> Google Cloud Shell <-。(我正在console.cloud.google.com中的命令提示符下工作)

我已经复制了这个基本的GO程序以连接到我的MySQL实例。

我构建并运行它。去建立mysqlexample.go ./mysqlexample

我无法成功建立连接。您可以看到我尝试过的所有各种连接字符串,它们的右边是我得到的响应。

我可以使用mysql admin从本地Windows计算机连接。

救命?

package main

import (
    "database/sql"
    _ "github.com/go-sql-driver/mysql"
    "log"
    )

func main() {

    const dbIP = "104.xxx.xx.x"
    const dbInstanceName =  "esp-1-dev:us-central1:espdev"
    const dbName = "servpro"
    const dbUserName = "root"
    const dbPassword = "xxxxxxx"

    const dbOpenString = dbUserName + ":" + dbPassword + "@/" + dbInstanceName + "/" + dbName  //GETS RESPONSE default addr for network 'AppEngine:Zone:Project' unknown
    //const dbOpenString = dbUserName + "@cloudsql(" + dbInstanceName + ")/" + dbName   //GETS RESPONSE  dial cloudsql: unknown network cloudsql
    //const dbOpenString = dbUserName + "@/"  //+ "?parseTime=true&loc=UTC"                 //GETS RESPONSE  getsockopt: connection refused
    //const dbOpenString = dbUserName + ":" + dbPassword + "@tcp(" + dbIP + ":3306)/" + dbName  //GETS RESPONSE  dial tcp 104.xxx.xxx.x:3306: getsockopt: connection timed out

    //  Got this from stack overflow.  GoDocs are not updated to reflect 2nd Gen databases.
    //  http://stackoverflow.com/questions/38890022/tls-requested-but-server-does-not-support-tls-error-with-google-cloud-sql-2nd
    //user:password@cloudsql(copiedPastedInstanceConnectionName)/d‌​atabaseName?charset=‌​charset&collation=co‌​llation&tls=tlsConfi‌​gName&parseTime=true
    //First Generation Connection String    
        //username:password@cloudsql(appID:CloudSQLInstance)/databasename?parseTime=true&loc=UTC

    db, err := sql.Open("mysql", dbOpenString);
    defer db.Close()

    log.Println("Attempting Ping of database....")

    err = db.Ping()

    if err != nil {
        log.Println("db.Ping() failed:  " + dbOpenString)
        log.Println(err)
    } else {
        log.Println("Success!")
    }

}

阅读 300

收藏
2020-07-02

共1个答案

一尘不染

以下是正确的连接字符串,但是它们取决于您从哪个版本的App Engine连接。

App Engine标准:

user:password@cloudsql(INSTANCE_CONNECTION_NAME)/dbname

App Engine弹性:

user:password@unix(/cloudsql/INSTANCE_CONNECTION_NAME)/dbname
2020-07-02