Using Google Cloud SQL

Google Cloud SQL provides a relational database that you can use with your App Engine application. Cloud SQL is a MySQL database that lives in Google's cloud. To learn more about Google Cloud SQL, see the Google Cloud SQL documentation.

For information on pricing and restrictions imposed by both Cloud SQL and App Engine, see Pricing and Access Limits.

Before you begin

  1. Create or select a Cloud Platform project in the Cloud Platform Console and then ensure that project includes an App Engine application:
    Go to App Engine

    The Dashboard opens if an App Engine application already exists in your project. Otherwise, you are prompted to choose the region where you want your App Engine application located.

  2. To deploy your app with the goapp and appcfg tools, you must download and install the App Engine SDK for Go:
    Download the App Engine SDK

Setting up the Cloud SQL instance

  1. Create a Second Generation Cloud SQL instance and configure the root user.
  2. If you don't want to use the root user to connect, create a user.
  3. Using the Cloud SDK, get the Cloud SQL instance connection name to use as a connection string in your application code:
    gcloud sql instances describe [INSTANCE_NAME]
    
    Record the value returned for connectionName. You can also find this value in the Instance details page of the Google Cloud Platform Console. For example, in the Cloud SDK output:
    $ gcloud sql instances describe instance1
    connectionName: project1:us-central1:instance1
    

Granting access to App Engine

If your App Engine application and Cloud SQL instance are in different Google Cloud Platform projects, you must use a service account to allow your App Engine application access to Cloud SQL.

This service account represents your App Engine application and is created by default when you create a Google Cloud Platform project.

  1. If your App Engine application is in the same project as your Cloud SQL instance, proceed to Setting up. Otherwise, proceed to the next step.
  2. Identify the service account associated with your App Engine application. The default App Engine service account is named [PROJECT-ID]@appspot.gserviceaccount.com.

    You can verify the App Engine service account on the IAM Permissions page. Ensure that you select the project for your App Engine application, not your Cloud SQL instance.

    Go to the IAM Permissions page

  3. Go to the IAM & Admin Projects page in the Google Cloud Platform Console.

    Go to the IAM & Admin Projects page

  4. Select the project that contains the Cloud SQL instance.
  5. Search for the service account name.
  6. If the service account is already there with the Editor role, you can proceed to Setting up.
  7. Otherwise, add the service account by clicking Add.
  8. In the Add members dialog, provide the name of the service account and select Project > Editor for the role.
  9. Click Add.

    You should now see the service account listed with the Editor role.

Setting up

  1. Add the Cloud SQL instance connection name, database name, user, and password to the environment variables in app.yaml.
    env_variables:
      # Replace INSTANCE_CONNECTION_NAME with the value obtained when configuring your
      # Cloud SQL instance, available from the Google Cloud Console or from the Cloud SDK.
      # For Cloud SQL 2nd generation instances, this should be in the form of "project:region:instance".
      CLOUDSQL_CONNECTION_NAME: INSTANCE_CONNECTION_NAME
      # Replace username and password if you aren't using the root user.
      CLOUDSQL_USER: root
      CLOUDSQL_PASSWORD: ''
    

Code sample overview

The following sample lists the databases on a Cloud SQL instance.

// Copyright 2016 Google Inc. All rights reserved.
// Use of this source code is governed by the Apache 2.0
// license that can be found in the LICENSE file.

// Sample cloudsql demonstrates connection to a Cloud SQL instance from App Engine standard.
package cloudsql

import (
	"bytes"
	"database/sql"
	"fmt"
	"log"
	"net/http"
	"os"

	_ "github.com/go-sql-driver/mysql"
)

func init() {
	http.HandleFunc("/", handler)
}

func handler(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path != "/" {
		http.NotFound(w, r)
		return
	}

	connectionName := mustGetenv("CLOUDSQL_CONNECTION_NAME")
	user := mustGetenv("CLOUDSQL_USER")
	password := os.Getenv("CLOUDSQL_PASSWORD") // NOTE: password may be empty

	w.Header().Set("Content-Type", "text/plain")

	db, err := sql.Open("mysql", fmt.Sprintf("%s:%s@cloudsql(%s)/", user, password, connectionName))
	if err != nil {
		http.Error(w, fmt.Sprintf("Could not open db: %v", err), 500)
		return
	}
	defer db.Close()

	rows, err := db.Query("SHOW DATABASES")
	if err != nil {
		http.Error(w, fmt.Sprintf("Could not query db: %v", err), 500)
		return
	}
	defer rows.Close()

	buf := bytes.NewBufferString("Databases:\n")
	for rows.Next() {
		var dbName string
		if err := rows.Scan(&dbName); err != nil {
			http.Error(w, fmt.Sprintf("Could not scan result: %v", err), 500)
			return
		}
		fmt.Fprintf(buf, "- %s\n", dbName)
	}
	w.Write(buf.Bytes())
}

func mustGetenv(k string) string {
	v := os.Getenv(k)
	if v == "" {
		log.Panicf("%s environment variable not set.", k)
	}
	return v
}

Deploying your app

To upload your app to App Engine, run the following command:

    goapp deploy cloudsql/

For details about deploying to App Engine, see Deploying a Go App.

Send feedback about...

App Engine standard environment for Go