import { Database, ObjectTypeInfo } from '@hw-agconnect/cloud/src/main/ets/database/Database'
import cloud from '@hw-agconnect/cloud'
import buffer from '@ohos.buffer'
// 云数据操作
export class CloudDataBase{
static cloudDataBase:Database|null
static async getCloudDatabase(){
if (!CloudDataBase.cloudDataBase) {
let value=await getContext().resourceManager.getRawFileContent('schema.json')
let json=buffer.from(value as ArrayBufferLike).toString('utf-8')
CloudDataBase.cloudDataBase=cloud.database({
objectTypeInfo:JSON.parse(json) as ObjectTypeInfo ,
zoneName:'question'//云中建的数据库名称
})
}
return CloudDataBase.cloudDataBase
}
}
操作数据库的表:
import { CloudDataBase } from '.'
import { UserInfo } from '../../models/question'
// 对云中的userinfo表中的增删改查
export class UserService{
//拿到了用户的这张表
static async getUserDatabase(){
let database=await CloudDataBase.getCloudDatabase();
return database.collection<UserInfo>(UserInfo)//拿到了用户的这张表
}
/**
*基础示例
* */
static async testInfo(userId:string){
let database=await CloudDataBase.getCloudDatabase();
let res=await database.collection<UserInfo>(UserInfo)
.query()
.limit(1)
.equalTo('user_id',userId)//比对,条件
.get()//拿到结果,是异步
return res
}
static async getUserInfo(userId:string){
let res=(await UserService.getUserDatabase())
.query()
.limit(1)
.equalTo('user_id',userId)//比对,条件
.get()//拿到结果,是异步
return res
}
/**
* 可用
* */
static async updataUserInfo(user:UserInfo){
let res=(await UserService.getUserDatabase())
.upsert(user)
return res
}
}
export class QuestionInfo{
static className:string='question_info'
id:number|null=null
classify_id:number=0
paper_id:number=0
title:string=''
order:number=0
question_type:string=''
answer_letter:string=''
answer_text:string=''
answer_solution:string=''
}
export class UserInfo{
static className:string='user_info'//和云数据库中的表名一致
id:number|null=null
avatar:string=''
nick_name:string=''
user_id:string=''
phone:string=''
}