当前位置:   article > 正文

#如何创新玩转HarmonyOS开发#端云一体化开发计算十二生肖-云数据库_harmonyos如何连接云数据库?

harmonyos如何连接云数据库?

1. 前言

上帖子使用云函数端云一体化开发计算十二生肖,此贴使用云数据库端云一体化开发计算十二生肖,在DevEco Studio可以完成端侧代码开发和云侧代码开发,一键部署云数据库,效果与之前使用云函数一样,计算获取方式不同。

2. 真机效果

3. 讲解

创建端云一体化项目,这里就不介绍的,创建、部署云数据库官方详细教程 开发云数据库-开发云工程-端云一体化开发-应用/服务开发-DevEco Studio使用指南(HarmonyOS)-工具-HarmonyOS应用开发 端云一体化项目结构和之前不一样,多了CloudProgram模块, 下面介绍项目开发,先从云侧开发开始,再到端侧开发。

4. 云侧开发

4.1 介绍云数据库目录结构

展开CloudProgram模块,展开clouddb目录,dataentry目录是存储数据条目文件,objecttype目录是存储对象类型文件,db-config.json自动生成,内容包含云数据库配置,目录结构如下图:

4.2 定义对象类型

     右击objecttype目录,创建对象类型

  1. {
  2. "fields": [
  3. {
  4. "belongPrimaryKey": true,
  5. "fieldName": "idx",
  6. "fieldType": "Integer",
  7. "isNeedEncrypt": false,
  8. "notNull": true
  9. },
  10. {
  11. "belongPrimaryKey": false,
  12. "fieldName": "zodiacName",
  13. "fieldType": "String",
  14. "isNeedEncrypt": false,
  15. "notNull": false
  16. }
  17. ],
  18. "indexes": [
  19. {
  20. "indexName": "idxIndex",
  21. "indexList": [
  22. {
  23. "fieldName": "idx",
  24. "sortType": "ASC"
  25. }
  26. ]
  27. },
  28. {
  29. "indexName": "zodiacIndex",
  30. "indexList": [
  31. {
  32. "fieldName": "zodiacName",
  33. "sortType": "DESC"
  34. }
  35. ]
  36. }
  37. ],
  38. "objectTypeName": "ZodiacObject",
  39. "permissions": [
  40. {
  41. "rights": [
  42. "Read"
  43. ],
  44. "role": "World"
  45. },
  46. {
  47. "rights": [
  48. "Read",
  49. "Upsert"
  50. ],
  51. "role": "Authenticated"
  52. },
  53. {
  54. "rights": [
  55. "Read",
  56. "Upsert",
  57. "Delete"
  58. ],
  59. "role": "Creator"
  60. },
  61. {
  62. "rights": [
  63. "Read",
  64. "Upsert",
  65. "Delete"
  66. ],
  67. "role": "Administrator"
  68. }
  69. ]
  70. }
复制

4.3 定义数据条目

     右击dataentry目录,创建数据条目

  1. {
  2. "cloudDBZoneName": "cloudDBZoneZodiac",
  3. "objectTypeName": "ZodiacObject",
  4. "objects": [
  5. {
  6. "idx": 0,
  7. "zodiacName": "猴"
  8. },
  9. {
  10. "idx": 1,
  11. "zodiacName": "鸡"
  12. },
  13. {
  14. "idx": 2,
  15. "zodiacName": "狗"
  16. },
  17. {
  18. "idx": 3,
  19. "zodiacName": "猪"
  20. },
  21. {
  22. "idx": 4,
  23. "zodiacName": "鼠"
  24. },
  25. {
  26. "idx": 5,
  27. "zodiacName": "牛"
  28. },
  29. {
  30. "idx": 6,
  31. "zodiacName": "虎"
  32. },
  33. {
  34. "idx": 7,
  35. "zodiacName": "兔"
  36. },
  37. {
  38. "idx": 8,
  39. "zodiacName": "龙"
  40. },
  41. {
  42. "idx": 9,
  43. "zodiacName": "蛇"
  44. },
  45. {
  46. "idx": 10,
  47. "zodiacName": "马"
  48. },
  49. {
  50. "idx": 11,
  51. "zodiacName": "羊"
  52. }
  53. ]
  54. }
复制

4.4 部署云数据库

     部署云侧代码到AGC上,右击clouddb目录,选择Deploy Cloud DB, 自动部署到AGC上,如果提示没有登录,登录成功后,再操作一次部署。

 4.5 导出文件格式

4.5.1 登录到AGC->云数据库,进入当前项目的云数据库服务菜单,可分别在“对象类型”、“存储区”与“数据”页签查看到您刚刚部署的云数据库资源。

4.5.2 导出json格式文件

4.5.3 导出js格式文件

4.5.3 导出json文件和js文件,端侧使用到。

5. 端侧开发

5.1 端侧模块结构

先看一下端侧模块结构:

5.2 common目录

目录放一些公共的封装类,比如Log类; components目录放自定义组件;entryability是自动生成的,里面有一个EntryAbility类,包含生命周期;pages目录放UI布局页面;services目录放业务逻辑类,比如调用云侧接口。

5.3 services目录

这里只介绍services目录的工作,先介绍如何和AGC连接上的,这里使用一个单独的文件来处理:

5.3.1 services目录下AgcConfig.ts

  1. import agconnect from '@hw-agconnect/api-ohos';
  2. import "@hw-agconnect/core-ohos";
  3. import "@hw-agconnect/auth-ohos";
  4. import '@hw-agconnect/auth-types-ohos';
  5. import { Log } from '../common/Log';
  6. const TAG = "[AGCConfig]";
  7. export function getAGConnect(context) {
  8. try {
  9. agconnect.instance().init(context);
  10. Log.info(TAG, "xx init AGC SDK success");
  11. return agconnect;
  12. }
  13. catch (err) {
  14. Log.error(TAG, "xx initAgcSDK failed" + err);
  15. }
  16. }
复制

5.3.2 在services目录下创建app-schema.json文件,复制上面在AGC下载的json格式文件内容到app-schema.json里

  1. {
  2. "schemaVersion": 1,
  3. "permissions": [{
  4. "permissions": [{
  5. "role": "World",
  6. "rights": ["Read"]
  7. }, {
  8. "role": "Authenticated",
  9. "rights": ["Read", "Upsert"]
  10. }, {
  11. "role": "Creator",
  12. "rights": ["Read", "Upsert", "Delete"]
  13. }, {
  14. "role": "Administrator",
  15. "rights": ["Read", "Upsert", "Delete"]
  16. }],
  17. "objectTypeName": "ZodiacObject"
  18. }],
  19. "objectTypes": [{
  20. "indexes": [{
  21. "indexName": "zodiacIndex",
  22. "indexList": [{
  23. "fieldName": "zodiacName",
  24. "sortType": "DESC"
  25. }]
  26. }, {
  27. "indexName": "idxIndex",
  28. "indexList": [{
  29. "fieldName": "idx",
  30. "sortType": "ASC"
  31. }]
  32. }],
  33. "objectTypeName": "ZodiacObject",
  34. "fields": [{
  35. "isNeedEncrypt": false,
  36. "fieldName": "idx",
  37. "notNull": true,
  38. "isSensitive": false,
  39. "belongPrimaryKey": true,
  40. "fieldType": "Integer"
  41. }, {
  42. "isNeedEncrypt": false,
  43. "fieldName": "zodiacName",
  44. "notNull": false,
  45. "isSensitive": false,
  46. "belongPrimaryKey": false,
  47. "fieldType": "String"
  48. }]
  49. }]
  50. }
复制

5.3.3 在services目录下创建ZodiacObject.js文件,复制上面在AGC下载的js格式文件内容到ZodiacObject.js里

  1. /*
  2. * Copyright (c) Huawei Technologies Co., Ltd. 2020-2020. All rights reserved.
  3. * Generated by the CloudDB ObjectType compiler. DO NOT EDIT!
  4. */
  5. class ZodiacObject {
  6. constructor() {
  7. this.idx = undefined;
  8. this.zodiacName = undefined;
  9. }
  10. setIdx(idx) {
  11. this.idx = idx;
  12. }
  13. getIdx() {
  14. return this.idx;
  15. }
  16. setZodiacName(zodiacName) {
  17. this.zodiacName = zodiacName;
  18. }
  19. getZodiacName() {
  20. return this.zodiacName;
  21. }
  22. }
  23. ZodiacObject.className = 'ZodiacObject';
  24. export {ZodiacObject}
复制

5.3.4 services目录下创建CloudDB.ts

  1. import * as schema from './app-schema.json';
  2. import { ZodiacObject } from './ZodiacObject'
  3. import { AGConnectCloudDB, CloudDBZone, CloudDBZoneQuery } from '@hw-agconnect/database-ohos';
  4. import { AGCRoutePolicy } from '@hw-agconnect/core-ohos';
  5. import { getAGConnect } from './AgcConfig';
  6. export class CloudDBService {
  7. private static ZONE_NAME: string = "cloudDBZoneZodiac"
  8. private static init(context: any): Promise<CloudDBZone> {
  9. return new Promise((resolve, reject) => {
  10. // 获取AGC连接
  11. getAGConnect(context);
  12. AGConnectCloudDB.initialize(context);
  13. AGConnectCloudDB.getInstance({
  14. context: context,
  15. agcRoutePolicy: AGCRoutePolicy.CHINA,
  16. objectTypeInfo: schema
  17. }).then((ret) => {
  18. return resolve(ret.openCloudDBZone(this.ZONE_NAME));
  19. }).catch((err) => {
  20. return reject(err);
  21. });
  22. })
  23. }
  24. public static query(context: any, year: number): Promise<ZodiacObject> {
  25. let idx = year%12;
  26. return new Promise((resolve, reject) => {
  27. const query = CloudDBZoneQuery.where(ZodiacObject).equalTo("idx", idx);
  28. this.init(context).then((ret) => {
  29. ret.executeQuery(query).then((ret) => {
  30. resolve(ret.getSnapshotObjects()[0]);
  31. })
  32. }).catch((err) => {
  33. reject(err);
  34. });
  35. })
  36. }
  37. }
复制

5.4 pages目录

目录 Index.ts 这里是页面布局,上面看到的效果,就是这里实现的。

  1. import { CloudDBService } from '../services/CloudDB';
  2. @Entry
  3. @Component
  4. struct Index {
  5. // 存储选择年份
  6. @State year: number = 2022
  7. // 计算出来生肖
  8. @State born: string = "?"
  9. // 是否在计算中
  10. @State flag: boolean = false
  11. // 计算生肖
  12. getBorn() {
  13. // 标识为计算中
  14. this.flag = true;
  15. console.info('xx Page year: ' + this.year)
  16. // 封装参数
  17. let params = {
  18. "year": this.year
  19. }
  20. // 调用云数据库
  21. CloudDBService.query(getContext(this), this.year).then((res) => {
  22. console.info('xx cloud db result: ' + JSON.stringify(res));
  23. // 计算完成
  24. this.flag = false;
  25. // 结果赋值给生肖变量
  26. this.born = res.zodiacName;
  27. }).catch((err) => {
  28. // 计算完成
  29. this.flag = false;
  30. console.error('xx error: ', err && err.message);
  31. });
  32. }
  33. build() {
  34. Stack() {
  35. if (!this.flag) {
  36. Column({space: 20}) {
  37. Text('请选择年份')
  38. .fontSize(20)
  39. .fontWeight(FontWeight.Bold)
  40. // 选择年份
  41. Column() {
  42. Text(this.year + '')
  43. .fontSize(20)
  44. .fontWeight(FontWeight.Bold)
  45. .padding(10)
  46. .width(100)
  47. .border({ width: 1, radius: 8 })
  48. }
  49. .bindMenu([
  50. { value: '2006', action: () => {this.year = 2006; this.born = '?'} },
  51. { value: '2007', action: () => {this.year = 2007; this.born = '?'} },
  52. { value: '2008', action: () => {this.year = 2008; this.born = '?'} },
  53. { value: '2009', action: () => {this.year = 2009; this.born = '?'} },
  54. { value: '2010', action: () => {this.year = 2010; this.born = '?'} },
  55. { value: '2011', action: () => {this.year = 2011; this.born = '?'} },
  56. { value: '2012', action: () => {this.year = 2012; this.born = '?'} },
  57. { value: '2013', action: () => {this.year = 2013; this.born = '?'} },
  58. { value: '2014', action: () => {this.year = 2014; this.born = '?'} },
  59. { value: '2015', action: () => {this.year = 2015; this.born = '?'} },
  60. { value: '2016', action: () => {this.year = 2016; this.born = '?'} },
  61. { value: '2017', action: () => {this.year = 2017; this.born = '?'} },
  62. { value: '2018', action: () => {this.year = 2018; this.born = '?'} },
  63. { value: '2019', action: () => {this.year = 2019; this.born = '?'} },
  64. { value: '2020', action: () => {this.year = 2020; this.born = '?'} },
  65. { value: '2021', action: () => {this.year = 2021; this.born = '?'} },
  66. { value: '2022', action: () => {this.year = 2022; this.born = '?'} },
  67. { value: '2023', action: () => {this.year = 2023; this.born = '?'} },
  68. { value: '2024', action: () => {this.year = 2024; this.born = '?'} },
  69. { value: '2025', action: () => {this.year = 2025; this.born = '?'} }
  70. ])
  71. // 计算按钮操作
  72. Button('计算', {type: ButtonType.Normal, stateEffect: true})
  73. .fontSize(18)
  74. .borderRadius(8)
  75. .width(100)
  76. .margin({bottom: 20})
  77. .onClick(() => {
  78. // 根据年份计算生肖
  79. this.getBorn()
  80. })
  81. // 显示计算结果
  82. Text(`${this.year} 年生肖是 ${this.born}`)
  83. .fontSize(20)
  84. .fontWeight(FontWeight.Bold)
  85. }
  86. .width('100%')
  87. .height('100%')
  88. .padding({top: '33%'})
  89. } else {
  90. // 计算中
  91. LoadingProgress().color(Color.Blue)
  92. .backgroundColor(Color.Transparent)
  93. }
  94. }
  95. }
  96. }
复制

6. 总结

由于调用云侧云数据库是异步的,不能马上返回结果,这里添加LoadingProgress组件,让用户知道在运行中,效果看得不是很明显,可能录制时,网速很快,LoadingProgress组件闪一下就不见了,如果遇到网络慢时,LoadingProgress就会一直转,直到云数据库返回响应时,再消失LoadingProgress。

进入华为专区,解锁更多内容

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/102559
推荐阅读
相关标签
  

闽ICP备14008679号