且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

谷歌应用程序引擎golang,驱动程序:连接不好

更新时间:2023-10-18 09:07:16

我最终需要更改我的dbcloud变量,以包含SQL服务器的区域改变它:

 'projectid:instancename'

收件人:

 'projectid:regionname:instancename'

不知道为什么我需要这样做,因为它不在 https://github.com/go-sql-driver/mysql ,但现在都可以使用!


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!

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!