Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Go database/sql é uma interface genérica
em torno de bancos de dados SQL (ou semelhantes a SQL) para a linguagem de programação Go. Para usar
database/sql com seu aplicativo, use o driver
database/sql do Spanner.
Instale o driver de banco de dados/SQL do Spanner.
Para usar o driver de banco de dados/SQL do Spanner no seu
aplicativo, adicione o seguinte módulo ao arquivo go.mod:
github.com/googleapis/go-sql-spanner
Usar o driver SQL/de banco de dados do Spanner
Para criar uma conexão de banco de dados/SQL com um banco de dados do Spanner, use spanner como o nome do driver e um nome de banco de dados totalmente qualificado como a string de conexão:
import("context""database/sql""fmt"_"github.com/googleapis/go-sql-spanner")funcconnect(projectId,instanceId,databaseIdstring)error{ctx:=context.Background()dsn:=fmt.Sprintf("projects/%s/instances/%s/databases/%s",projectId,instanceId,databaseId)db,err:=sql.Open("spanner",dsn)iferr!=nil{returnfmt.Errorf("failed to open database connection: %v",err)}deferfunc(){_=db.Close()}()fmt.Printf("Connected to %s\n",dsn)row:=db.QueryRowContext(ctx,"select @greeting","Hello from Spanner")vargreetingstringiferr:=row.Scan(&greeting);err!=nil{returnfmt.Errorf("failed to get greeting: %v",err)}fmt.Printf("Greeting: %s\n",greeting)returnnil}
Para ter a melhor performance possível ao usar o driver database/sql do Spanner, siga estas práticas recomendadas:
Parâmetros de consulta: use parâmetros de consulta em vez de valores inline em instruções SQL. Isso permite que o Spanner armazene em cache e
reutilize o plano de execução para instruções SQL usadas com frequência.
Transações somente leitura: use transações somente leitura para cargas de trabalho que apenas leem dados. As transações somente leitura não são bloqueadas.
Registre um problema no GitHub
para relatar uma solicitação de recurso ou um bug, ou para fazer uma pergunta sobre
o driver SQL/de banco de dados do Spanner.
[[["Fácil de entender","easyToUnderstand","thumb-up"],["Meu problema foi resolvido","solvedMyProblem","thumb-up"],["Outro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Informações incorretas ou exemplo de código","incorrectInformationOrSampleCode","thumb-down"],["Não contém as informações/amostras de que eu preciso","missingTheInformationSamplesINeed","thumb-down"],["Problema na tradução","translationIssue","thumb-down"],["Outro","otherDown","thumb-down"]],["Última atualização 2025-08-25 UTC."],[],[],null,["# Use the Spanner database/sql driver\n\n[Go database/sql](https://pkg.go.dev/database/sql) is a generic interface\naround SQL (or SQL-like) databases for the Go programming language. To use\ndatabase/sql with your application, use the [Spanner\ndatabase/sql driver](https://github.com/googleapis/go-sql-spanner).\n\nThe Spannerdatabase/sql driver supports both\nGoogleSQL-dialect databases and PostgreSQL-dialect databases.\n\nInstall the Spanner database/sql driver\n---------------------------------------\n\nTo use the Spanner database/sql driver in your\napplication, add the following module to your `go.mod` file: \n\n github.com/googleapis/go-sql-spanner\n\nUse the Spanner database/sql driver\n-----------------------------------\n\nTo create a database/sql connection to a Spanner\ndatabase, use `spanner` as the driver name and a fully qualified database name\nas the connection string: \n\n### GoogleSQL\n\n import (\n \t\"context\"\n \t\"database/sql\"\n \t\"fmt\"\n\n \t_ \"github.com/googleapis/go-sql-spanner\"\n )\n\n func connect(projectId, instanceId, databaseId string) error {\n \tctx := context.Background()\n \tdsn := fmt.Sprintf(\"projects/%s/instances/%s/databases/%s\",\n \t\tprojectId, instanceId, databaseId)\n \tdb, err := sql.Open(\"spanner\", dsn)\n \tif err != nil {\n \t\treturn fmt.Errorf(\"failed to open database connection: %v\", err)\n \t}\n \tdefer func() { _ = db.Close() }()\n\n \tfmt.Printf(\"Connected to %s\\n\", dsn)\n \trow := db.QueryRowContext(ctx, \"select @greeting\", \"Hello from Spanner\")\n \tvar greeting string\n \tif err := row.Scan(&greeting); err != nil {\n \t\treturn fmt.Errorf(\"failed to get greeting: %v\", err)\n \t}\n \tfmt.Printf(\"Greeting: %s\\n\", greeting)\n\n \treturn nil\n }\n\n### PostgreSQL\n\n import (\n \t\"context\"\n \t\"database/sql\"\n \t\"fmt\"\n\n \t_ \"github.com/googleapis/go-sql-spanner\"\n )\n\n func connect(projectId, instanceId, databaseId string) error {\n \tctx := context.Background()\n \tdsn := fmt.Sprintf(\"projects/%s/instances/%s/databases/%s\",\n \t\tprojectId, instanceId, databaseId)\n \tdb, err := sql.Open(\"spanner\", dsn)\n \tif err != nil {\n \t\treturn fmt.Errorf(\"failed to open database connection: %v\", err)\n \t}\n \tdefer func() { _ = db.Close() }()\n\n \tfmt.Printf(\"Connected to %s\\n\", dsn)\n \t// The Spanner database/sql driver supports both PostgreSQL-style query\n \t// parameters ($1, $2, ...) and positional query parameters (?, ?, ...).\n \t// This example uses PostgreSQL-style parameters.\n \trow := db.QueryRowContext(ctx, \"select $1\", \"Hello from Spanner PostgreSQL\")\n \tvar greeting string\n \tif err := row.Scan(&greeting); err != nil {\n \t\treturn fmt.Errorf(\"failed to get greeting: %v\", err)\n \t}\n \tfmt.Printf(\"Greeting: %s\\n\", greeting)\n\n \treturn nil\n }\n\nFor more information, see the [Spanner\ndatabase/sql driver GitHub repository](https://github.com/googleapis/go-sql-spanner).\n\nSupported features\n------------------\n\nThe [Spanner Go database/sql examples code directory](https://github.com/googleapis/go-sql-spanner/blob/-/examples)\ncontains ready-to-run examples for commonly used Spanner features.\n\nPerformance tips\n----------------\n\nTo get the best possible performance when using the Spanner\ndatabase/sql driver, follow these best practices:\n\n- Query parameters: [Use query parameters](https://github.com/googleapis/go-sql-spanner/blob/-/examples/query-parameters/main.go) instead of inline values in SQL statements. This lets Spanner cache and reuse the execution plan for frequently used SQL statements.\n- Database Definition Language (DDL): [Group multiple DDL statements into one\n batch](https://github.com/googleapis/go-sql-spanner/blob/-/examples/ddl-batches/main.go) instead of executing them one by one.\n- Data Manipulation Language (DML): [Group multiple DML statements into one\n batch](https://github.com/googleapis/go-sql-spanner/blob/-/examples/dml-batches/main.go) instead of executing them one by one.\n- Read-only transactions: [Use read-only transactions](https://github.com/googleapis/go-sql-spanner/blob/-/examples/read-only-transactions/main.go) for workloads that only read data. Read-only transactions don't take locks.\n- Tags: [Use request and transaction tags](https://github.com/googleapis/go-sql-spanner/blob/-/examples/tags/main.go) to [troubleshoot](/spanner/docs/introspection/troubleshooting-with-tags).\n\nWhat's next\n-----------\n\n- Learn more about using Spanner with the database/sql driver [code examples](https://github.com/googleapis/go-sql-spanner/blob/-/examples).\n- Learn more about [database/sql](https://pkg.go.dev/database/sql).\n- Use [GORM with Spanner](/spanner/docs/use-gorm).\n- [File a GitHub issue](https://github.com/googleapis/go-sql-spanner/issues) to report a feature request or bug, or to ask a question about the Spanner database/sql driver."]]