Obtenir ou créer
Restez organisé à l'aide des collections
Enregistrez et classez les contenus selon vos préférences.
Obtenir ou créer dans une transaction
En savoir plus
Pour obtenir une documentation détaillée incluant cet exemple de code, consultez les articles suivants :
Exemple de code
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.
[[["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"]],[],[[["\u003cp\u003eThis content demonstrates how to use transactions in Google Cloud Datastore to either retrieve an existing entity or create a new one if it doesn't exist.\u003c/p\u003e\n"],["\u003cp\u003eCode samples are provided in C#, Go, Java, Node.js, PHP, Python, and Ruby, illustrating the process of getting or creating an entity within a transaction.\u003c/p\u003e\n"],["\u003cp\u003eThe examples show how to look up an entity using its key and how to insert or save the entity into the database using the \u003ccode\u003etransaction\u003c/code\u003e class functions.\u003c/p\u003e\n"],["\u003cp\u003eThe content links to the documentation for Cloud Datastore transactions, as well as instructions for setting up client libraries and authentication.\u003c/p\u003e\n"],["\u003cp\u003eThe page also provides links to the specific API reference documentation for each of the languages showcased in the samples.\u003c/p\u003e\n"]]],[],null,["# Get or create in a transaction.\n\nExplore further\n---------------\n\n\nFor detailed documentation that includes this code sample, see the following:\n\n- [Cloud Datastore Transactions](/datastore/docs/concepts/cloud-datastore-transactions)\n- [Transactions](/datastore/docs/concepts/transactions)\n\nCode sample\n-----------\n\n### C#\n\n\nTo learn how to install and use the client library for Datastore mode, see\n[Datastore mode client libraries](/datastore/docs/reference/libraries).\n\n\nFor more information, see the\n[Datastore mode C# API\nreference documentation](https://cloud.google.com/dotnet/docs/reference/Google.Cloud.Datastore.V1/latest).\n\n\nTo authenticate to Datastore mode, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n Entity task;\n using (var transaction = _db.BeginTransaction())\n {\n task = transaction.Lookup(_sampleTask.Key);\n if (task == null)\n {\n transaction.Insert(_sampleTask);\n transaction.Commit();\n }\n }\n\n### Go\n\n\nTo learn how to install and use the client library for Datastore mode, see\n[Datastore mode client libraries](/datastore/docs/reference/libraries).\n\n\nFor more information, see the\n[Datastore mode Go API\nreference documentation](https://cloud.google.com/go/docs/reference/cloud.google.com/go/datastore/latest).\n\n\nTo authenticate to Datastore mode, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n _, err := client.RunInTransaction(ctx, func(tx *datastore.Transaction) error {\n \tvar task Task\n \tif err := tx.Get(key, &task); err != datastore.ErrNoSuchEntity {\n \t\treturn err\n \t}\n \t_, err := tx.Put(key, &Task{\n \t\tCategory: \"Personal\",\n \t\tDone: false,\n \t\tPriority: 4,\n \t\tDescription: \"Learn Cloud Datastore\",\n \t})\n \treturn err\n })\n\n### Java\n\n\nTo learn how to install and use the client library for Datastore mode, see\n[Datastore mode client libraries](/datastore/docs/reference/libraries).\n\n\nFor more information, see the\n[Datastore mode Java API\nreference documentation](https://cloud.google.com/java/docs/reference/google-cloud-datastore/latest/history).\n\n\nTo authenticate to Datastore mode, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n Entity task;\n Transaction txn = datastore.newTransaction();\n try {\n task = txn.get(taskKey);\n if (task == null) {\n task = Entity.newBuilder(taskKey).build();\n txn.put(task);\n txn.commit();\n }\n } finally {\n if (txn.isActive()) {\n txn.rollback();\n }\n }\n\n### Node.js\n\n\nTo learn how to install and use the client library for Datastore mode, see\n[Datastore mode client libraries](/datastore/docs/reference/libraries).\n\n\nFor more information, see the\n[Datastore mode Node.js API\nreference documentation](https://cloud.google.com/nodejs/docs/reference/datastore/latest).\n\n\nTo authenticate to Datastore mode, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n async function getOrCreate(taskKey, taskData) {\n const taskEntity = {\n key: taskKey,\n data: taskData,\n };\n const transaction = datastore.transaction();\n\n try {\n await transaction.run();\n const [task] = await transaction.get(taskKey);\n if (task) {\n // The task entity already exists.\n await transaction.rollback();\n } else {\n // Create the task entity.\n transaction.save(taskEntity);\n await transaction.commit();\n }\n return taskEntity;\n } catch (err) {\n await transaction.rollback();\n }\n }\n\n### PHP\n\n\nTo learn how to install and use the client library for Datastore mode, see\n[Datastore mode client libraries](/datastore/docs/reference/libraries).\n\n\nFor more information, see the\n[Datastore mode PHP API\nreference documentation](https://googleapis.github.io/google-cloud-php/#/docs/cloud-datastore/latest).\n\n\nTo authenticate to Datastore mode, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n $transaction = $datastore-\u003etransaction();\n $entity = $transaction-\u003elookup($task-\u003ekey());\n if ($entity === null) {\n $entity = $transaction-\u003einsert($task);\n $transaction-\u003ecommit();\n }\n\n### Python\n\n\nTo learn how to install and use the client library for Datastore mode, see\n[Datastore mode client libraries](/datastore/docs/reference/libraries).\n\n\nFor more information, see the\n[Datastore mode Python API\nreference documentation](https://cloud.google.com/python/docs/reference/datastore/latest).\n\n\nTo authenticate to Datastore mode, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n from google.cloud import https://cloud.google.com/python/docs/reference/datastore/latest/\n\n # For help authenticating your client, visit\n # https://cloud.google.com/docs/authentication/getting-started\n client = https://cloud.google.com/python/docs/reference/datastore/latest/.https://cloud.google.com/python/docs/reference/datastore/latest/google.cloud.datastore.client.Client.html()\n\n import datetime\n\n with client.https://cloud.google.com/python/docs/reference/datastore/latest/google.cloud.datastore.client.Client.html#google_cloud_datastore_client_Client_transaction():\n key = client.https://cloud.google.com/python/docs/reference/datastore/latest/google.cloud.datastore.client.Client.html#google_cloud_datastore_client_Client_key(\n \"Task\", datetime.datetime.now(tz=datetime.timezone.utc).isoformat()\n )\n\n task = client.https://cloud.google.com/python/docs/reference/datastore/latest/google.cloud.datastore.client.Client.html#google_cloud_datastore_client_Client_get(key)\n\n if not task:\n task = https://cloud.google.com/python/docs/reference/datastore/latest/.https://cloud.google.com/python/docs/reference/datastore/latest/google.cloud.datastore.entity.Entity.html(key)\n task.update({\"description\": \"Example task\"})\n client.https://cloud.google.com/python/docs/reference/datastore/latest/google.cloud.datastore.client.Client.html#google_cloud_datastore_client_Client_put(task)\n\n return task\n\n### Ruby\n\n\nTo learn how to install and use the client library for Datastore mode, see\n[Datastore mode client libraries](/datastore/docs/reference/libraries).\n\n\nFor more information, see the\n[Datastore mode Ruby API\nreference documentation](/ruby/docs/reference/google-cloud-datastore/latest).\n\n\nTo authenticate to Datastore mode, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n task = nil\n datastore.transaction do |tx|\n task = tx.find task_key\n if task.nil?\n task = datastore.entity task_key do |t|\n t[\"category\"] = \"Personal\"\n t[\"done\"] = false\n t[\"priority\"] = 4\n t[\"description\"] = \"Learn Cloud Datastore\"\n end\n tx.save task\n end\n end\n\nWhat's next\n-----------\n\n\nTo search and filter code samples for other Google Cloud products, see the\n[Google Cloud sample browser](/docs/samples?product=datastore)."]]