Create a TCP connection when using Go

Demonstrates opening a TCP connection to Cloud SQL for SQL Server using Go's database/sql package.

Documentation pages that include this code sample

To view the code sample used in context, see the following documentation:

Code sample


var (
	dbUser    = mustGetenv("DB_USER") // e.g. 'my-db-user'
	dbPwd     = mustGetenv("DB_PASS") // e.g. 'my-db-password'
	dbTCPHost = mustGetenv("DB_HOST") // e.g. '' ('' if deployed to GAE Flex)
	dbPort    = mustGetenv("DB_PORT") // e.g. '1433'
	dbName    = mustGetenv("DB_NAME") // e.g. 'my-database'

dbURI := fmt.Sprintf("server=%s;user id=%s;password=%s;port=%s;database=%s;", dbTCPHost, dbUser, dbPwd, dbPort, dbName)

// dbPool is the pool of database connections.
dbPool, err := sql.Open("mssql", dbURI)
if err != nil {
	return nil, fmt.Errorf("sql.Open: %v", err)

// ...

return dbPool, nil

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.