我得到以下错误:
Could not query db: Error 1046: No database selected
我了解错误消息的含义。但是我找不到说明如何选择数据库的文档。
这是我的代码:
package main
import (
"database/sql"
"fmt"
"log"
"net/http"
"os"
"time"
"google.golang.org/appengine"
_ "github.com/go-sql-driver/mysql"
)
var db *sql.DB
func main() {
var (
connectionName = mustGetenv("CLOUDSQL_CONNECTION_NAME")
user = mustGetenv("CLOUDSQL_USER")
password = os.Getenv("CLOUDSQL_PASSWORD")
)
var err error
db, err = sql.Open("mysql ", fmt.Sprintf("%s:%s@cloudsql(%s)/", user, password, connectionName))
if err != nil {
log.Fatalf("Could not open db: %v", err)
}
http.HandleFunc("/", handler)
appengine.Main()
}
func handler(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/" {
http.NotFound(w, r)
return
}
w.Header().Set("Content-Type", "text/plain")
rows, err := db.Query("INSERT INTO ping ( ping ) VALUES ( '" + time.Now().Format("2006-01-02 03:04:05") + "' );")
if err != nil {
http.Error(w, fmt.Sprintf("Could not query db: %v", err), 500)
return
}
defer rows.Close()
w.Write([]byte("OK"))
}
func mustGetenv(k string) string {
v := os.Getenv(k)
if v == "" {
log.Panicf("%s environment variable not set.", k)
}
return v
}
看起来您指定了CONNECTION_NAME
,但没有指定DB_NAME
。根据文档(向下滚动到" Go> companion Process"部分(,您应该打开连接:
import (
"github.com/go-sql-driver/mysql"
)
dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s",
dbUser,
dbPassword,
"127.0.0.1:3306",
dbName)
db, err := sql.Open("mysql", dsn)
此代码类似于您的代码,但您没有指定dbName
参数。请记住,其余配置应保持与您在代码中共享的相同,但您应该只需将数据库的名称附加到sql.Open()
函数的第二个参数。
在使用GO连接从App Engine弹性到Cloud SQL的示例中,确定了相同的过程:
db, err = sql.Open("mysql", dbName)
所以我想您应该尝试此更改:
// Old connection opening
db, err = sql.Open("mysql ", fmt.Sprintf("%s:%s@cloudsql(%s)/", user, password, connectionName))
// New connection opening, including dbName
db, err = sql.Open("mysql ", fmt.Sprintf("%s:%s@cloudsql(%s)/%s", user, password, connectionName, dbName))
我本人并不真正熟悉Golang,但是根据文档应该有效。