Restez organisé à l'aide des collections
Enregistrez et classez les contenus selon vos préférences.
Go database/sql est une interface générique autour des bases de données SQL (ou de type SQL) pour le langage de programmation Go. Pour utiliser database/sql avec votre application, utilisez le pilote Spanner database/sql.
Installer le pilote de base de données/SQL Spanner
Pour utiliser le pilote de base de données/SQL Spanner dans votre application, ajoutez le module suivant à votre fichier go.mod :
github.com/googleapis/go-sql-spanner
Utiliser le pilote de base de données/SQL Spanner
Pour créer une connexion de base de données/SQL à une base de données Spanner, utilisez spanner comme nom de pilote et un nom de base de données complet comme chaîne de connexion :
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}
Pour obtenir les meilleures performances possibles lorsque vous utilisez le pilote SQL/de base de données Spanner, suivez ces bonnes pratiques :
Paramètres de requête : utilisez des paramètres de requête au lieu de valeurs intégrées dans les instructions SQL. Cela permet à Spanner de mettre en cache et de réutiliser le plan d'exécution pour les instructions SQL fréquemment utilisées.
Transactions en lecture seule : utilisez des transactions en lecture seule pour les charges de travail qui ne font que lire des données. Les transactions en lecture seule ne peuvent pas être verrouillées.
Ouvrez une demande sur GitHub pour signaler une demande de fonctionnalité ou un bug, ou pour poser une question sur le pilote SQL/de base de données Spanner.
Sauf indication contraire, le contenu de cette page est régi par une licence Creative Commons Attribution 4.0, et les échantillons de code sont régis par une licence Apache 2.0. Pour en savoir plus, consultez les Règles du site Google Developers. Java est une marque déposée d'Oracle et/ou de ses sociétés affiliées.
Dernière mise à jour le 2025/08/25 (UTC).
[[["Facile à comprendre","easyToUnderstand","thumb-up"],["J'ai pu résoudre mon problème","solvedMyProblem","thumb-up"],["Autre","otherUp","thumb-up"]],[["Difficile à comprendre","hardToUnderstand","thumb-down"],["Informations ou exemple de code incorrects","incorrectInformationOrSampleCode","thumb-down"],["Il n'y a pas l'information/les exemples dont j'ai besoin","missingTheInformationSamplesINeed","thumb-down"],["Problème de traduction","translationIssue","thumb-down"],["Autre","otherDown","thumb-down"]],["Dernière mise à jour le 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."]]