在鸿蒙(HarmonyOS 5)中使用 DevEco Studio 实现单词读写功能,可以通过本地数据库存储和操作单词数据。以下是详细步骤和代码示例
1. 环境准备
- DevEco Studio:确保安装最新版本(支持HarmonyOS 5)。
- 项目配置:创建一个
Empty Ability项目,选择Stage模型。 - 权限申请:在
module.json5中声明数据库权限(若需操作外部存储):{"module": {"requestPermissions": [{"name": "ohos.permission.READ_USER_STORAGE","reason": "读取单词数据"},{"name": "ohos.permission.WRITE_USER_STORAGE","reason": "写入单词数据"}]} }
2. 数据库设计
使用鸿蒙的关系型数据库(@ohos.data.relationalStore)存储单词数据。
(1)定义单词数据模型
// model/WordModel.ts
export interface Word {id?: number; // 自增主键english: string;chinese: string;createTime?: number; // 时间戳
}
(2)初始化数据库
// database/WordDB.ts
import relationalStore from '@ohos.data.relationalStore';
import { Word } from '../model/WordModel';const DB_NAME = 'word_db';
const TABLE_NAME = 'word';
const SQL_CREATE_TABLE = `CREATE TABLE IF NOT EXISTS ${TABLE_NAME} (id INTEGER PRIMARY KEY AUTOINCREMENT,english TEXT NOT NULL,chinese TEXT NOT NULL,createTime INTEGER)`;export class WordDB {private static instance: WordDB;private rdbStore: relationalStore.RdbStore | null = null;private constructor() {}public static async getInstance(): Promise<WordDB> {if (!WordDB.instance) {WordDB.instance = new WordDB();await WordDB.instance.initDB();}return WordDB.instance;}private async initDB(): Promise<void> {const context = getContext(this) as Context;const config: relationalStore.StoreConfig = {name: DB_NAME,securityLevel: relationalStore.SecurityLevel.S1};this.rdbStore = await relationalStore.getRdbStore(context, config);await this.rdbStore.executeSql(SQL_CREATE_TABLE);}// 插入单词async addWord(word: Word): Promise<number> {if (!this.rdbStore) throw new Error('Database not initialized');const valueBucket: relationalStore.ValuesBucket = {'english': word.english,'chinese': word.chinese,'createTime': new Date().getTime()};return await this.rdbStore.insert(TABLE_NAME, valueBucket);}// 查询所有单词async getAllWords(): Promise<Word[]> {if (!this.rdbStore) throw new Error('Database not initialized');const predicates = new relationalStore.RdbPredicates(TABLE_NAME);const columns = ['id', 'english', 'chinese', 'createTime'];const result = await this.rdbStore.query(predicates, columns);const words: Word[] = [];while (result.goToNextRow()) {words.push({id: result.getLong(result.getColumnIndex('id')),english: result.getString(result.getColumnIndex('english')),chinese: result.getString(result.getColumnIndex('chinese')),createTime: result.getLong(result.getColumnIndex('createTime'))});}result.close();return words;}// 删除单词async deleteWord(id: number): Promise<void> {if (!this.rdbStore) throw new Error('Database not initialized');const predicates = new relationalStore.RdbPredicates(TABLE_NAME);predicates.equalTo('id', id);await this.rdbStore.delete(predicates);}
}
3. 实现单词读写UI
(1)单词列表页面
// pages/WordList.ets
import { WordDB } from '../database/WordDB';
import { Word } from '../model/WordModel';@Entry
@Component
struct WordList {@State wordList: Word[] = [];@State newWord: Word = { english: '', chinese: '' };async aboutToAppear() {await this.loadWords();}async loadWords() {const db = await WordDB.getInstance();this.wordList = await db.getAllWords();}async addWord() {if (!this.newWord.english || !this.newWord.chinese) return;const db = await WordDB.getInstance();await db.addWord(this.newWord);this.newWord = { english: '', chinese: '' };await this.loadWords();}async deleteWord(id: number) {const db = await WordDB.getInstance();await db.deleteWord(id);await this.loadWords();}build() {Column() {// 输入框Row() {TextInput({ placeholder: '英文' }).width('40%').onChange((value: string) => this.newWord.english = value)TextInput({ placeholder: '中文' }).width('40%').onChange((value: string) => this.newWord.chinese = value)Button('添加').onClick(() => this.addWord())}.padding(10)// 单词列表List({ space: 10 }) {ForEach(this.wordList, (word: Word) => {ListItem() {Row() {Column() {Text(word.english).fontSize(18)Text(word.chinese).fontSize(14).opacity(0.6)}.layoutWeight(1)Button('删除').onClick(() => this.deleteWord(word.id!))}}.padding(10).borderRadius(10).backgroundColor('#FFF')})}.layoutWeight(1).width('100%')}.width('100%').height('100%').padding(12).backgroundColor('#F5F5F5')}
}
4. 关键点说明
- 数据库操作:
- 使用
@ohos.data.relationalStore实现增删改查。 - 通过
RdbPredicates构建查询条件。
- 使用
- 数据绑定:
@State装饰器实现数据变化自动刷新UI。
- 异步处理:
- 所有数据库操作需用
async/await处理。
- 所有数据库操作需用
- UI组件:
TextInput用于输入单词,List+ForEach展示数据。
5. 扩展功能
(1)单词搜索
// 在WordDB.ts中添加方法
async searchWords(keyword: string): Promise<Word[]> {const predicates = new relationalStore.RdbPredicates(TABLE_NAME);predicates.contains('english', keyword).or().contains('chinese', keyword);// ... 同query逻辑
}// 在页面中添加搜索框
TextInput({ placeholder: '搜索' }).onChange((value: string) => {if (value) {db.searchWords(value).then(words => this.wordList = words);} else {this.loadWords();}})
(2)数据导出/导入
- 导出:将数据库内容转为JSON文件:
const words = await db.getAllWords(); const content = JSON.stringify(words); // 使用@ohos.file.fs写入文件 - 导入:解析JSON文件后批量插入数据库。
6. 效果预览
| 功能 | 截图描述 |
|---|---|
| 添加单词 | 输入英文和中文后点击"添加"按钮 |
| 单词列表 | 卡片式展示所有存储的单词 |
| 删除单词 | 点击卡片右侧的"删除"按钮 |
