DEV Community

ι™ˆζ¨
ι™ˆζ¨

Posted on

HarmonyOS5-CloudDB-Guide-EN

🌟 A Guide to Using Huawei CloudDB in HarmonyOS 🌟


Hey there, fellow developers!
Today, let's talk about integrating and using Huawei CloudDB in HarmonyOS applications. Whether you're new to HarmonyOS development or looking to optimize your existing data management logic, this guide will walk you through data CRUD (Create, Read, Update, Delete) operations and other super practical advanced query features!


πŸ”₯ Core Features & Use Cases

Huawei CloudDB provides lightweight, high-performance cloud data storage with support for real-time synchronization and data encryption. With simple API calls, you can quickly achieve data persistence, complex queries, and multi-device synchronization. Here are the details of frequently used operations πŸ‘‡


πŸ“₯ Writing Data (Upsert)

Function Description:

  • The upsert() method is used to write or update data:
    • If the primary key of the data already exists, the record is updated.
    • If it does not exist, a new record is created.
  • It supports single or batch writes (as an atomic operationβ€”either all succeed or all fail).

Important Notes:

  1. When performing a batch write, all objects must be of the same type.
  2. The total data size cannot exceed 2MB, with a maximum of 1000 records per write.

Code Example:

async function upsertBook() {
  try {
    const record = await cloud
      .database({
        objectTypeInfo: schema,
        zoneName: "QuickStartDemo"
      })
      .collection("BookInfo")
      .upsert({
        "id": 2000,
        "bookName": "book_name",
        "author": "huawei",
        "price": 1020
      });
    console.log("Upsert successful, count:", record);
  } catch (err) {
    console.error("Upsert failed:", JSON.stringify(err));
  }
}
Enter fullscreen mode Exit fullscreen mode

πŸ” Querying Data (Query)

1. Simple Queries

  • Query all data:
async function queryAllBooks() {
  const result = await cloud.database(...).collection("BookInfo").query().get();
  console.log("All books:", result);
}
Enter fullscreen mode Exit fullscreen mode
  • Conditional query (e.g., where bookName equals "Zuo Zhuan"):
query().equalTo("bookName", "Zuo Zhuan").get();
Enter fullscreen mode Exit fullscreen mode

2. Compound Queries

  • Combining multiple conditions (AND/OR logic):
// Query for books related to 'Database' with a price between 20 and 50
query()
  .contains("bookName", "Database")
  .greaterThan("price", 20)
  .and()
  .lessThan("price", 50)
  .get();

// Query for 'Database' books with a price < 20 or > 50
query()
  .contains("bookName", "Database")
  .lessThan("price", 20)
  .or()
  .greaterThan("price", 50)
  .get();
Enter fullscreen mode Exit fullscreen mode

3. Sorting and Pagination

  • Sort by price in descending order:
query()
  .lessThan("price", 50)
  .orderByDesc("price")
  .get();
Enter fullscreen mode Exit fullscreen mode
  • Paginated query (skip the first 5, take 10):
query()
  .lessThan("price", 50)
  .orderByDesc("price")
  .limit(10, 5) // limit(count, offset)
  .get();
Enter fullscreen mode Exit fullscreen mode

πŸ—‘οΈ Deleting Data (Delete)

Function Description:

  • Deletes single or multiple records based on the primary key (atomic operation).

Code Example:

async function deleteBook() {
  try {
    const count = await cloud.database(...).collection("BookInfo").delete({ "id": 2000 });
    console.log("Delete successful, count:", count);
  } catch (err) {
    console.error("Delete failed:", err);
  }
}
Enter fullscreen mode Exit fullscreen mode

πŸš€ Best Practices & Pitfalls to Avoid

  1. Performance Optimization:
    • Avoid frequent small data writes; prefer batch operations.
    • For complex queries, try to pre-filter on the server-side to reduce data transfer volume.
  2. Error Handling:
    • It is recommended to wrap all operations in a try-catch block to handle asynchronous exceptions.
  3. Security Recommendations:
    • Enable field-level encryption for sensitive data (e.g., user phone numbers).

🌈 Summary

Huawei CloudDB makes data management in HarmonyOS applications easy and efficient! With the code examples and tips in this article, you should now have a good grasp of the core CRUD operations. Go ahead and give it a try! If you run into any issues, feel free to ask in the comments section and discuss with other developers.

Happy coding and may your code be bug-free! πŸš€


I hope this guide becomes a powerful tool in your development arsenal! If you found it helpful, don't forget to share it with your friends~ 😊

Top comments (0)