google app engine golang, driver: bad connection

2020-03-25 08:06发布

I have some code that is working on the local GAE server but once I publish it to GAE it throws the error "driver: bad connection".

Below code generates a new *sql.DB:

func NewDb() (*sql.DB, error) {
  cloud := os.Getenv("dbcloud")
  local := os.Getenv("dblocal")
  if appengine.IsDevAppServer() {
    return sql.Open("mysql", "root@tcp("+local+":3306)/dbo")
  }
  return sql.Open("mysql", "root@cloudsql("+cloud+")/dbo")
}

In my app.yaml I have the following:

env_variables:
  dbcloud: 'projectid:instancename'
  dblocal: 'xxx.xxx.xxx.xxx'

It seems to return a new *sql.DB correctly but once I start using prepared statements is when things start to break.

db, err := NewDb() // err is nil
stmt, err := db.Prepare("INSERT INTO dbo.Users (Id) VALUES (?)") // err is driver: bad connection

I've been fighting with this for an hour now and i'm probably doing something very stupid any help would be appreciated!

1条回答
我欲成王,谁敢阻挡
2楼-- · 2020-03-25 08:53

I ended up needing to change my dbcloud variable to include the region of the SQL server changing it from:

'projectid:instancename'

To:

'projectid:regionname:instancename'

No idea why I need to do this as it's not in the docs of https://github.com/go-sql-driver/mysql but is all working now!

查看更多
登录 后发表回答