Usa el controlador de SQL o la base de datos de Spanner
Organiza tus páginas con colecciones
Guarda y categoriza el contenido según tus preferencias.
Go database/sql es una interfaz genérica para bases de datos SQL (o similares a SQL) para el lenguaje de programación Go. Para usar database/sql con tu aplicación, usa el controlador database/sql de Spanner.
Instala el controlador de base de datos o SQL de Spanner
Para usar el controlador database/sql de Spanner en tu aplicación, agrega el siguiente módulo a tu archivo go.mod:
github.com/googleapis/go-sql-spanner
Usa el controlador de base de datos o SQL de Spanner
Para crear una conexión de base de datos o SQL a una base de datos de Spanner, usa spanner como nombre del controlador y un nombre de base de datos completamente calificado como la cadena de conexión:
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 obtener el mejor rendimiento posible cuando uses el controlador database/sql de Spanner, sigue estas prácticas recomendadas:
Parámetros de consulta: Usa parámetros de consulta en lugar de valores intercalados en las instrucciones de SQL. Esto permite que Spanner almacene en caché y reutilice el plan de ejecución para las instrucciones de SQL que se usan con frecuencia.
Transacciones de solo lectura: Usa transacciones de solo lectura para cargas de trabajo que solo leen datos. Las transacciones de solo lectura no aceptan bloqueos.
Presenta un problema en GitHub para informar un error o solicitar una función, o bien para hacer una pregunta sobre el controlador database/sql de Spanner.
[[["Fácil de comprender","easyToUnderstand","thumb-up"],["Resolvió mi problema","solvedMyProblem","thumb-up"],["Otro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Información o código de muestra incorrectos","incorrectInformationOrSampleCode","thumb-down"],["Faltan la información o los ejemplos que necesito","missingTheInformationSamplesINeed","thumb-down"],["Problema de traducción","translationIssue","thumb-down"],["Otro","otherDown","thumb-down"]],["Última actualización: 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."]]