David Symonds | ccbe394 | 2015-12-07 00:16:23 | [diff] [blame] | 1 | // Copyright 2013 Google Inc. All rights reserved. |
| 2 | // Use of this source code is governed by the Apache 2.0 |
| 3 | // license that can be found in the LICENSE file. |
| 4 | |
| 5 | /* |
| 6 | Package cloudsql exposes access to Google Cloud SQL databases. |
| 7 | |
David Symonds | a503df9 | 2016-03-23 02:00:38 | [diff] [blame] | 8 | This package does not work in App Engine "flexible environment". |
David Symonds | ccbe394 | 2015-12-07 00:16:23 | [diff] [blame] | 9 | |
| 10 | This package is intended for MySQL drivers to make App Engine-specific |
| 11 | connections. Applications should use this package through database/sql: |
| 12 | Select a pure Go MySQL driver that supports this package, and use sql.Open |
| 13 | with protocol "cloudsql" and an address of the Cloud SQL instance. |
| 14 | |
| 15 | A Go MySQL driver that has been tested to work well with Cloud SQL |
| 16 | is the go-sql-driver: |
Zev Goldstein | 0c7f7a8 | 2022-07-12 16:28:29 | [diff] [blame] | 17 | |
David Symonds | ccbe394 | 2015-12-07 00:16:23 | [diff] [blame] | 18 | import "database/sql" |
| 19 | import _ "github.com/go-sql-driver/mysql" |
| 20 | |
| 21 | db, err := sql.Open("mysql", "user@cloudsql(project-id:instance-name)/dbname") |
| 22 | |
David Symonds | ccbe394 | 2015-12-07 00:16:23 | [diff] [blame] | 23 | Another driver that works well with Cloud SQL is the mymysql driver: |
Zev Goldstein | 0c7f7a8 | 2022-07-12 16:28:29 | [diff] [blame] | 24 | |
David Symonds | ccbe394 | 2015-12-07 00:16:23 | [diff] [blame] | 25 | import "database/sql" |
| 26 | import _ "github.com/ziutek/mymysql/godrv" |
| 27 | |
| 28 | db, err := sql.Open("mymysql", "cloudsql:instance-name*dbname/user/password") |
| 29 | |
David Symonds | ccbe394 | 2015-12-07 00:16:23 | [diff] [blame] | 30 | Using either of these drivers, you can perform a standard SQL query. |
| 31 | This example assumes there is a table named 'users' with |
| 32 | columns 'first_name' and 'last_name': |
| 33 | |
| 34 | rows, err := db.Query("SELECT first_name, last_name FROM users") |
| 35 | if err != nil { |
| 36 | log.Errorf(ctx, "db.Query: %v", err) |
| 37 | } |
| 38 | defer rows.Close() |
| 39 | |
| 40 | for rows.Next() { |
| 41 | var firstName string |
| 42 | var lastName string |
| 43 | if err := rows.Scan(&firstName, &lastName); err != nil { |
| 44 | log.Errorf(ctx, "rows.Scan: %v", err) |
| 45 | continue |
| 46 | } |
| 47 | log.Infof(ctx, "First: %v - Last: %v", firstName, lastName) |
| 48 | } |
| 49 | if err := rows.Err(); err != nil { |
| 50 | log.Errorf(ctx, "Row error: %v", err) |
| 51 | } |
| 52 | */ |
| 53 | package cloudsql |
| 54 | |
| 55 | import ( |
| 56 | "net" |
| 57 | ) |
| 58 | |
| 59 | // Dial connects to the named Cloud SQL instance. |
| 60 | func Dial(instance string) (net.Conn, error) { |
| 61 | return connect(instance) |
| 62 | } |