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

Connecting to CloudSQL from App Engine (Second Generation CloudSQL) GO

喜欢 Stack,我的第一个 post 完全是出于沮丧。感谢您的评论!

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

我建造它 运行 它。 去建造 mysqlexample.go ./mysql例子

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

我可以使用 mysql 管理员从本地 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.
    //  
    //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!")
    }

}

以下是正确的连接字符串,但它们会根据您连接的 App Engine 版本而有所不同。

App 引擎标准:

user:password@cloudsql(INSTANCE_CONNECTION_NAME)/dbname

App Engine 灵活:

user:password@unix(/cloudsql/INSTANCE_CONNECTION_NAME)/dbname

https://cloud.google.com/appengine/docs/flexible/go/using-cloud-sql

对于 GO、App Engine 和 Cloud 的新手SQL 只需编写最简单的 GO 程序来连接您的 Cloud 并与之通信SQL 第二代数据库令人沮丧!

您可以做出选择,App Eng 或 App Eng Flex,SQL 第一代或第二代...。连接字符串因组合而异。当您搜索时,google 的所有文档都会将您带到第一代 SQL 和没有 flex 的 App Engine,因为这是生产中的主要内容。如果您这样做,请确保您正在阅读 Flex 文档。如果这样做,请确保您正在阅读第二代文档。有时它们是完全不同的文档,有时文档堆叠在一个页面上,您必须到底部才能看到更新的东西 2nd gen sql 和 app eng flex。

CloudShell 很棘手,我仍然无法编译 GO 并与这里的 SQL 2nd 交谈。我正在使用 SQL PROXY 运行 与已部署的应用程序引擎 flex 成功地与云 sql 第二代通信,您必须使用 SQL PROXY。您必须完成在 appengine 和 SQL.

上创建用户的设置

这是我的工作程序。

package main

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

func healthCheckHandler(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "ok")
}

func main() {
http.HandleFunc("/", handle)
http.HandleFunc("/_cloudshellProxy/_ah/health", healthCheckHandler)
log.Print("Listening on port 8080")
log.Fatal(http.ListenAndServe(":8080", nil))
}


func handle(w http.ResponseWriter, r *http.Request) {

const dbIP = "104.xxx.xxx.x"
const dbInstanceName =  "projectname:us-central1:sqlinstance"
const dbName = "servxxx"
const dbUserName = "sqlproxysuser"
const dbPassword = "xxxRockxxx"


if r.URL.Path != "/" {
    http.NotFound(w, r)
    return
}
fmt.Fprint(w, "Hello SQL!  Hello?")
fmt.Fprint(w, "\n")

const dbOpenString = dbUserName + ":" + dbPassword + "@unix(/cloudsql/" + dbInstanceName + ")/" + dbName 
//const dbOpenString = dbUserName + ":" + dbPassword + "@cloudsql(" + dbInstanceName + ")/" + dbName 

//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
//-=- SQL OPEN Statement,  per docs, DOES NOT return an error ever
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
//-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=--=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
db, err := sql.Open("mysql", dbOpenString);
defer db.Close()

err = db.Ping()
if err != nil {
    fmt.Fprint(w, "Failed Connection" + "  " + dbOpenString)
    fmt.Fprint(w, "\n")
    fmt.Fprint(w, err)
    return
} else {
    fmt.Fprint(w, "SUCCESSFUL CONNECTION" + "  " + dbOpenString)
    fmt.Fprint(w, "\n")
}

_, err = db.Exec("CREATE TABLE IF NOT EXISTS exercisecloudsql101 (id INT NOT NULL AUTO_INCREMENT, name VARCHAR(100) NOT NULL, description TEXT, PRIMARY KEY (id))")
if err != nil {
    fmt.Fprint(w, "CREATE TABLE failed:")
    fmt.Fprint(w, "\n")
    fmt.Fprint(w, err) 
    fmt.Fprint(w, "\n")
} else {
    fmt.Fprint(w, "SUCCESSFUL CreateTable" + "  " + dbOpenString)
    fmt.Fprint(w, "\n")
}

}

运行 遇到了连接到云 SQL 实例的相同问题。下面是我在 windows localhost 环境中使用的一种变体。我的本地主机的 IP 需要添加到数据库实例的授权网络中。

Windows 本地主机通过 tcp 连接:

user:password@tcp(104.xxx.xxx.xxx:3306)/dbname

如果您要迁移到第二代 Go App Engine (Golang 1.11),请更改您的连接字符串:

user:password@cloudsql(instanceID)/db

user:password@unix(/cloudsql/instanceID)/db