π 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:
- When performing a batch write, all objects must be of the same type.
- 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));
}
}
π 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);
}
-
Conditional query (e.g., where
bookNameequals "Zuo Zhuan"):
query().equalTo("bookName", "Zuo Zhuan").get();
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();
3. Sorting and Pagination
- Sort by price in descending order:
query()
.lessThan("price", 50)
.orderByDesc("price")
.get();
- Paginated query (skip the first 5, take 10):
query()
.lessThan("price", 50)
.orderByDesc("price")
.limit(10, 5) // limit(count, offset)
.get();
ποΈ 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);
}
}
π Best Practices & Pitfalls to Avoid
- 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.
- Error Handling:
- It is recommended to wrap all operations in a
try-catchblock to handle asynchronous exceptions.
- It is recommended to wrap all operations in a
- 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)