Update
Tetap teratur dengan koleksi
Simpan dan kategorikan konten berdasarkan preferensi Anda.
Menggunakan update dalam transaksi.
Mempelajari lebih lanjut
Untuk dokumentasi mendetail yang menyertakan contoh kode ini, lihat artikel berikut:
Contoh kode
Kecuali dinyatakan lain, konten di halaman ini dilisensikan berdasarkan Lisensi Creative Commons Attribution 4.0, sedangkan contoh kode dilisensikan berdasarkan Lisensi Apache 2.0. Untuk mengetahui informasi selengkapnya, lihat Kebijakan Situs Google Developers. Java adalah merek dagang terdaftar dari Oracle dan/atau afiliasinya.
[[["Mudah dipahami","easyToUnderstand","thumb-up"],["Memecahkan masalah saya","solvedMyProblem","thumb-up"],["Lainnya","otherUp","thumb-up"]],[["Sulit dipahami","hardToUnderstand","thumb-down"],["Informasi atau kode contoh salah","incorrectInformationOrSampleCode","thumb-down"],["Informasi/contoh yang saya butuhkan tidak ada","missingTheInformationSamplesINeed","thumb-down"],["Masalah terjemahan","translationIssue","thumb-down"],["Lainnya","otherDown","thumb-down"]],[],[[["\u003cp\u003eThis content demonstrates how to use transactions to update multiple entities in Google Cloud Datastore, ensuring data consistency.\u003c/p\u003e\n"],["\u003cp\u003eThe code examples show a fund transfer scenario, where money is deducted from one account and added to another within a single transaction.\u003c/p\u003e\n"],["\u003cp\u003eThe provided examples demonstrate the transaction pattern, including starting a transaction, retrieving multiple entities, updating them, and then committing the changes or rolling back in case of failure.\u003c/p\u003e\n"],["\u003cp\u003eCode samples are available in multiple programming languages including C#, Go, Java, Node.js, PHP, Python, and Ruby, illustrating how to perform transactions in each language.\u003c/p\u003e\n"],["\u003cp\u003eThe documentation also provides information on how to install and use client libraries for Datastore, as well as set up authentication.\u003c/p\u003e\n"]]],[],null,["# Update\n\nUse an update 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 private void TransferFunds(Key fromKey, Key toKey, long amount)\n {\n using (var transaction = _db.BeginTransaction())\n {\n var entities = transaction.Lookup(fromKey, toKey);\n entities[0][\"balance\"].IntegerValue -= amount;\n entities[1][\"balance\"].IntegerValue += amount;\n transaction.Update(entities);\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 type BankAccount struct {\n \tBalance int\n }\n\n const amount = 50\n keys := []*datastore.Key{to, from}\n tx, err := client.NewTransaction(ctx)\n if err != nil {\n \tlog.Fatalf(\"client.NewTransaction: %v\", err)\n }\n accs := make([]BankAccount, 2)\n if err := tx.GetMulti(keys, accs); err != nil {\n \ttx.Rollback()\n \tlog.Fatalf(\"tx.GetMulti: %v\", err)\n }\n accs[0].Balance += amount\n accs[1].Balance -= amount\n if _, err := tx.PutMulti(keys, accs); err != nil {\n \ttx.Rollback()\n \tlog.Fatalf(\"tx.PutMulti: %v\", err)\n }\n if _, err = tx.Commit(); err != nil {\n \tlog.Fatalf(\"tx.Commit: %v\", 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 void transferFunds(Key fromKey, Key toKey, long amount) {\n Transaction txn = datastore.newTransaction();\n try {\n List\u003cEntity\u003e entities = txn.fetch(fromKey, toKey);\n Entity from = entities.get(0);\n Entity updatedFrom =\n Entity.newBuilder(from).set(\"balance\", from.getLong(\"balance\") - amount).build();\n Entity to = entities.get(1);\n Entity updatedTo =\n Entity.newBuilder(to).set(\"balance\", to.getLong(\"balance\") + amount).build();\n txn.put(updatedFrom, updatedTo);\n txn.commit();\n } finally {\n if (txn.isActive()) {\n txn.rollback();\n }\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 transferFunds(fromKey, toKey, amount) {\n const transaction = datastore.transaction();\n await transaction.run();\n const results = await Promise.all([\n transaction.get(fromKey),\n transaction.get(toKey),\n ]);\n const accounts = results.map(result =\u003e result[0]);\n\n accounts[0].balance -= amount;\n accounts[1].balance += amount;\n\n transaction.save([\n {\n key: fromKey,\n data: accounts[0],\n },\n {\n key: toKey,\n data: accounts[1],\n },\n ]);\n\n return await transaction.commit();\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 /**\n * Update two entities in a transaction.\n *\n * @param string $fromKeyId\n * @param string $toKeyId\n * @param int $amount\n * @param string $namespaceId\n */\n function transfer_funds(\n string $fromKeyId,\n string $toKeyId,\n int $amount,\n string $namespaceId = null\n ) {\n $datastore = new DatastoreClient(['namespaceId' =\u003e $namespaceId]);\n $transaction = $datastore-\u003etransaction();\n $fromKey = $datastore-\u003ekey('Account', $fromKeyId);\n $toKey = $datastore-\u003ekey('Account', $toKeyId);\n // The option 'sort' is important here, otherwise the order of the result\n // might be different from the order of the keys.\n $result = $transaction-\u003elookupBatch([$fromKey, $toKey], ['sort' =\u003e true]);\n if (count($result['found']) != 2) {\n $transaction-\u003erollback();\n }\n $fromAccount = $result['found'][0];\n $toAccount = $result['found'][1];\n $fromAccount['balance'] -= $amount;\n $toAccount['balance'] += $amount;\n $transaction-\u003eupdateBatch([$fromAccount, $toAccount]);\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 def transfer_funds(client, from_key, to_key, amount):\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 from_account = client.https://cloud.google.com/python/docs/reference/datastore/latest/google.cloud.datastore.client.Client.html#google_cloud_datastore_client_Client_get(from_key)\n to_account = client.https://cloud.google.com/python/docs/reference/datastore/latest/google.cloud.datastore.client.Client.html#google_cloud_datastore_client_Client_get(to_key)\n\n from_account[\"balance\"] -= amount\n to_account[\"balance\"] += amount\n\n client.https://cloud.google.com/python/docs/reference/datastore/latest/google.cloud.datastore.client.Client.html#google_cloud_datastore_client_Client_put_multi([from_account, to_account])\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 def transfer_funds from_key, to_key, amount\n datastore.transaction do |tx|\n from = tx.find from_key\n from[\"balance\"] -= amount\n to = tx.find to_key\n to[\"balance\"] += amount\n tx.save from, to\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)."]]